我正在尝试在 jupyter notebook 中运行以下代码。
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 是什么,但我没有收到此错误。
最佳答案
通常这样的脚本作为独立文件运行,例如
python foo.py 23 inches
Shell 将字符串列表中的“23 英寸”转换为字符串列表,该列表在程序中作为 sys.argv[1:]
提供。
parser.parse_args()
默认使用此 sys.argv[1:]
。但是当从 Ipython session 或笔记本中运行时,该列表具有初始化 session 的值。作为无效整数值给出的文件名是该初始化的一部分,您的解析器
无法使用。
要测试此脚本,您需要提供相关的字符串列表,例如
parser.parse_args(['23', 'lbs'])
或导入 sys
并修改 sys.argv
,如链接答案之一所述。
https://docs.python.org/3/library/argparse.html#beyond-sys-argv
关于Python argparse 错误 : error: argument count: invalid int value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50360012/