0
python -i prog.py -h

When calling the above command I get the expected output with a traceback and 'SystemExit: 0'. Without '-i' I get the expected output without a traceback. Why does this happen and is there a way to use both python flags and program flags in the same command without the traceback?

2
  • Difficult to tell without seeing your code. A basic example that I just tried works without issue. What platform are you running on? Windows? Linux? Commented Nov 8, 2016 at 17:24
  • @scotty3785 I am running on linux (ubuntu 15.10). Commented Nov 8, 2016 at 17:34

2 Answers 2

1

Running Python with the -i flag changes the handling of the SystemExit exception, which is used for things like sys.exit. Normally, an uncaught SystemExit causes Python to silently exit. However, with -i on, SystemExit is treated like any other exception, with a traceback and everything.

If you want to silence SystemExit tracebacks with -i on, you'll need to explicitly catch and ignore them. For example,

def main():
    try:
        ...
    except SystemExit:
        # Catch the exception to silence the traceback when running under python -i
        pass

if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

2 Comments

Ah ok, so this has nothing to do with argparse and everything to do with exiting in interactive mode. Should I go ahead and delete this question to avoid confusion?
@Jay: It seems like the question could be useful to future readers. I'd leave it.
1

From the docs:

exception SystemExit
This exception is raised by the sys.exit() function. When it is not handled, the Python interpreter exits; no stack traceback is printed.

argparse employs the SystemExit exception with the '-h' option, and since you enter interactive mode with the command line argument '-i' you see the traceback. Notice that the traceback is not printed if you implement and send in a different option:

python -i prog.py -p 80

Two immediate "quick-fixes" I can think of (but really, it comes down to what do you really need this for?)

  1. Put in a try-except clause when parsing your arguments.

  2. python -i prog.py -h 2> /dev/null

Comments

Your Answer

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.