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

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

问题描述

我正在尝试在 jupyter notebook 中运行以下代码.

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天全站免登陆