2

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.

user1251007
  • 15,891
  • 14
  • 50
  • 76

2 Answers2

1

yes.

>>> import sys
>>> sys.version

I do not want to print it in every run of that script, just in the case where an error has occurred.

Use try, except statements

Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99
1

You can change sys.excepthook to include the desired behavior. Just add the following to the beginning of your script:

import sys
def my_except_hook(exctype, value, traceback):
        print("Using python version {0}".format(sys.version))
        sys.__excepthook__(exctype, value, traceback)
sys.excepthook = my_except_hook

If an error is raised in your code, the python version is printed in addition to the normal error message.

user1251007
  • 15,891
  • 14
  • 50
  • 76