I have a python script that is called by the user by for example python script.py
or python3 script.py
. If this script raises an error, it is of importance which python version was used.
Surely, I could ask the user for the command that was used to execute script.py, however this might not resolve the python version. python
could be an alias for python3.4
or python2.7
.
I know that I could just print sys.version
in my script. But I do not want to print it in every run of that script, just in the case where an error has occurred.
So another idea was to simply wrap the whole script in an try, except
block.
import sys
try:
# original content of script.py
except:
print("Using python version {0}".format(sys.version))
raise
However that does not look very pythonic to me. So is there a more elegant solution to add sys.version
to each error message?
This question is not a duplicate of How do I check what version of Python is running my script?, as I do not want to check for the version information. My script should run with all versions of python. However, a custom message (in this case sys.version
) should be appended to the stacktrace.