Python argparse 错误 : error: argument count: invalid int value

标签 python jupyter-notebook argparse

我正在尝试在 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/

相关文章:

python - 如何让 mod_wsgi 接我的 virtualenv

python - 处理时的 Jupyter Notebook 计数器

python - 为什么在 argparse 中, 'True' 总是 'True' ?

python - argparse 和单元测试 python

python - OpenCV python : Show images in channel's color and not in grayscale

python - Python 和 Kivy 中带有线程的进度条

python - Django queryset - 从 json 对象转换

python - 操作系统错误 : cannot load library 'C:\Program Files\R\R-4.0.2\bin\x64\R.dll' : error 0x7e

google-cloud-platform - 浏览器在模型训练期间断开连接

python - argparse 错误 : Option not recognized