Python argparse错误:错误:参数计数:无效的int值 [英] Python argparse error: error: argument count: invalid int value

查看:272
本文介绍了Python argparse错误:错误:参数计数:无效的int值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在jupyter笔记本中的代码下运行.

I am trying to run below code in 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是什么,但我没有得到这个错误.

I am just trying to learn what argparse is but I don't get this error.

推荐答案

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

Normally a script like that is run as a stand alone file, e.g.

python foo.py 23 inches

shell会在字符串列表中转换"23英寸",该字符串可以在程序内的 sys.argv [1:] 中找到.

The shell converts '23 inches' in a list of strings, which is available as sys.argv[1:] inside the program.

parser.parse_args()

使用此 sys.argv [1:] 作为默认设置.但是,当从Ipython会话或Notebook内部运行时,该列表具有初始化该会话的值.作为无效整数值给出的文件名是该初始化的一部分,并且您的 parser 无法使用.

uses this sys.argv[1:] as the default. But when run from within a Ipython session or Notebook, that list has the values that initialized the session. That file name given as an invalid integer value was part of that initialization, and isn't usable by your parser.

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

To test this script you need to provide a relevant list of strings, e.g.

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

或导入 sys 并按照链接答案之一中的说明修改 sys.argv .

Or import sys and modify sys.argv as described in one of the linked answers.

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

这篇关于Python argparse错误:错误:参数计数:无效的int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆