【问题标题】:Python argparse error: error: argument count: invalid int valuePython argparse 错误:错误:参数计数:无效的 int 值
【发布时间】:2018-05-15 22:28:58
【问题描述】:

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


【解决方案1】:

通常这样的脚本作为独立文件运行,例如

python foo.py 23 inches

shell 将字符串列表中的“23 英寸”转换为程序中的sys.argv[1:]

parser.parse_args()

使用这个sys.argv[1:] 作为默认值。但是当从 Ipython 会话或笔记本中运行时,该列表具有初始化会话的值。作为无效整数值给出的文件名是该初始化的一部分,您的parser 无法使用。

要测试此脚本,您需要提供相关的字符串列表,例如

parser.parse_args(['23', 'lbs'])

或导入sys 并修改sys.argv,如链接答案之一所述。

https://docs.python.org/3/library/argparse.html#beyond-sys-argv

【讨论】:

    猜你喜欢
    • 2019-01-11
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多