我正在尝试在jupyter笔记本中运行以下代码。
import argparse
parser = argparse.ArgumentParser(description='Example with non-optional arguments')
parser.add_argument('count', action="store", type=int)
parser.add_argument('units', action="store")
print(parser.parse_args())
但是这给出了以下错误
usage: ipykernel_launcher.py [-h] count units
ipykernel_launcher.py: error: argument count: invalid int value: 'C:\\Users\\Kwan Lee\\AppData\\Roaming\\jupyter\\runtime\\kernel-76bf5bb5-ea74-42d5-8164-5c56b75bfafc.json'
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
c:\users\kwan lee\anaconda2\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py:2971: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
我只是想了解argparse是什么,但我没有得到这个错误。
答案 0 :(得分:0)
通常,像这样的脚本作为独立文件运行,例如
python foo.py 23 inches
外壳转换为23英寸'在一个字符串列表中,在程序中以sys.argv[1:]
形式提供。
parser.parse_args()
使用此sys.argv[1:]
作为默认值。但是当从Ipython会话或Notebook中运行时,该列表具有初始化会话的值。作为无效整数值给出的文件名是初始化的一部分,并且parser
无法使用。
要测试此脚本,您需要提供相关的字符串列表,例如
parser.parse_args(['23', 'lbs'])
或导入sys
并修改sys.argv
,如其中一个链接答案中所述。
https://docs.python.org/3/library/argparse.html#beyond-sys-argv