argparse 在使用[-h]时显示帮助,然后就退出了,如何才能不退出交互界面,等待下一个输入?
while True:
cmd = input('>>>')
parser = argparse.ArgumentParser()
parser.add_argument('-f', help='foo')
parser.parse_args(cmd.split())
这样输入[-h]的时候:
>>>-h
usage: test.py [-h] [-f F]
optional arguments:
-h, --help show this help message and exit
-f F foo
程序就结束了,现在我只要'show this help message',而不需要'exit',请问要如何做?谢谢!
根本原因在于,
argparse.parse_args()
会在出错和-h
时执行sys.exit()
. 这个可以通过捕获SystemExit
异常来解决:另外1: 建议不要把初始化代码放在循环块中, 我觉得这样写会更好:
另外2: 提出 python 问题时, 不妨注明你用的是 python2 还是 python3. 你的代码中, 有些规则在两个版本间有区别.
参考 -
argparse.parse_args()
源码片段: