Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

python - SystemExit: 2 error when calling parse_args() within ipython

I'm learning basics of Python and got already stuck at the beginning of argparse tutorial. I'm getting the following error:

import argparse
parser = argparse.ArgumentParser()
args = parser.parse_args()
usage: __main__.py [-h] echo
__main__.py: error: unrecognized arguments: -f
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

a %tb command gives the following output:

SystemExit                                Traceback (most recent call last)
<ipython-input-16-843cc484f12f> in <module>()
----> 1 args = parser.parse_args()

C:UsersHaikAnaconda2libargparse.pyc in parse_args(self, args, namespace)
   1702         if argv:
   1703             msg = _('unrecognized arguments: %s')
-> 1704             self.error(msg % ' '.join(argv))
   1705         return args
   1706 

C:UsersHaikAnaconda2libargparse.pyc in error(self, message)
   2372         """
   2373         self.print_usage(_sys.stderr)
-> 2374         self.exit(2, _('%s: error: %s
') % (self.prog, message))

C:UsersHaikAnaconda2libargparse.pyc in exit(self, status, message)
   2360         if message:
   2361             self._print_message(message, _sys.stderr)
-> 2362         _sys.exit(status)
   2363 
   2364     def error(self, message):

SystemExit: 2

How could I fix this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

argparse is a module designed to parse the arguments passed from the command line, so for example if you type the following at a command prompt:

$ python my_programme.py --arg1=5 --arg2=7

You can use argparse to interpret the --arg1=5 --arg2=7 part. If argparse thinks the arguments are invalid, it exits, which in general is done in python by calling sys.exit() which raises the SystemExit error, which is what you're seeing.

So the problem is you're trying to use argparse from an interactive interpreter (looks like ipython), and at this point the programme has already started, so the args should have already been parsed.

To try it properly create a separate python file such as my_programme.py and run it using python from a command line, as I illustrated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...