0

我很惊讶以前没有人问过这个问题,但不知何故我找不到答案。

SystemExit简单的加注时my_script.py

import sys

sys.exit(2)

运行时不显示回溯python my_script.py,如python doc中所述:

SystemExit:未处理时,Python解释器退出;不打印堆栈回溯。

但是,当使用 运行时ipython,会打印回溯:

$ ipython my_script.py
---------------------------------------------------------------------------
SystemExit                                Traceback (most recent call last)
my_script.py in <module>
      2 import sys
      3 
----> 4 sys.exit(2)

SystemExit: 2

如果解析失败,这是使用argparseas parser.parse_args()call时的问题。sys.exit()因此,用户看到的是无用的SystemExit: 2,而不是在回溯上方打印的错误消息。

一种解决方法是使用os._exit,但这感觉非常hacky并且可能无法正确清理。

是否有一个ipython标志会在SystemExit引发时沉默/隐藏回溯,就像标准python解释器一样?

4

1 回答 1

0

这是一个带有xmode“plain”的示例会话:

In [1]: import argparse
In [2]: parser=argparse.ArgumentParser()
In [3]: parser.add_argument('foo')
Out[3]: _StoreAction(option_strings=[], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
In [4]: import sys; sys.argv
Out[4]: 
['/usr/local/bin/ipython3',
 '--pylab',
 'qt',
 '--nosep',
 '--term-title',
 '--InteractiveShellApp.pylab_import_all=False',
 '--TerminalInteractiveShell.xmode=Plain']
In [5]: parser.parse_args()
usage: ipython3 [-h] foo
ipython3: error: unrecognized arguments: --pylab --nosep --term-title --InteractiveShellApp.pylab_import_all=False --TerminalInteractiveShell.xmode=Plain
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2

/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py:3426: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
In [6]: parser.parse_args([])
usage: ipython3 [-h] foo
ipython3: error: the following arguments are required: foo
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2

/usr/local/lib/python3.8/dist-packages/IPython/core/interactiveshell.py:3426: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

这显示了解析器生成的错误消息,然后是捕获和回溯。这使我能够以交互方式继续。

使用普通解释器,我收到消息,然后退出。

2310:~/mypy$ python3
Python 3.8.5 (default, Jan 27 2021, 15:41:15) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import argparse
>>> parser=argparse.ArgumentParser()
>>> parser.add_argument('foo');
_StoreAction(option_strings=[], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args()
usage: [-h] foo
: error: the following arguments are required: foo
2311:~/mypy$ 

对我来说,使用的全部目的ipython是尝试多种事情,而不会让我放弃。否则我会在没有交互层的情况下运行脚本。

于 2021-03-04T07:09:25.130 回答