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.

asked Jun 26, 2017 at 14:27
1
  • 2
    If you use logging you can add that to the output format Commented Jun 26, 2017 at 14:31

2 Answers 2

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

answered Jun 26, 2017 at 14:29
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Jun 28, 2017 at 18:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.