Jonathan
Jonathan

Reputation: 1402

How to use argparse with both python and program flags?

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?

Upvotes: 0

Views: 68

Answers (2)

Jared N
Jared N

Reputation: 162

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

Upvotes: 1

user2357112
user2357112

Reputation: 280953

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()

Upvotes: 1

Related Questions