SystemExit:在 ipython 中调用 parse_args() 时出现 2 错误 [英] SystemExit: 2 error when calling parse_args() within ipython

查看:19
本文介绍了SystemExit:在 ipython 中调用 parse_args() 时出现 2 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Python 的基础知识,但在开始 argparse 教程时已经陷入困境.我收到以下错误:

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

%tb 命令给出以下输出:

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:\Users\Haik\Anaconda2\lib\argparse.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:\Users\Haik\Anaconda2\lib\argparse.pyc in error(self, message)
   2372         """
   2373         self.print_usage(_sys.stderr)
-> 2374         self.exit(2, _('%s: error: %s\n') % (self.prog, message))

C:\Users\Haik\Anaconda2\lib\argparse.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?

推荐答案

argparse 是一个模块,旨在解析从命令行传递的参数,例如如果在命令提示符下键入以下内容:

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

您可以使用 argparse 来解释 --arg1=5 --arg2=7 部分.如果 argparse 认为参数无效,它会退出,这通常在 python 中通过调用 sys.exit() 来完成,这会引发 SystemExit错误,这就是您所看到的.

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.

所以问题是您试图从交互式解释器(看起来像 ipython)中使用 argparse,此时程序已经启动,因此 args 应该已经被解析.

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.

要尝试正确创建一个单独的 python 文件,例如 my_programme.py 并使用 python 从命令行运行它,如我所示.

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.

这篇关于SystemExit:在 ipython 中调用 parse_args() 时出现 2 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆