Python argparse 将参数存储为列表而不是整数.混淆还是正确? [英] Python argparse storing arguments as lists rather than ints. Confusing or correct?
问题描述
我正在使用两个测试脚本来自学如何在 Python 中使用 argparse
和 subprocess
库.我对 add_argument()
中的 type=int
值感到困惑.
I am using two test scripts to teach myself how to use argparse
and subprocess
libraries in Python. I am confused about the type=int
value in add_argument()
.
calculator.py:
calculator.py:
import sys
x = int(sys.argv[1])
y = int(sys.argv[2])
print(x,y)
print(x+y)
wrapper.py:
wrapper.py:
from subprocess import run
import argparse
import sys
parser = argparse.ArgumentParser(description='Wrapper.')
parser.add_argument('-x', nargs=1, type=int, dest='x', default=0, help='x.', required=True)
parser.add_argument('-y', nargs=1, type=int, dest='y', default=0, help='y.', required=True)
args = parser.parse_args()
if len(sys.argv) == 1:
parser.print_help()
else:
print('args.x and args.y')
run(["python","calculator.py", str(args.x), str(args.y)])
print('args.x[0] and args.y[0]')
run(["python","calculator.py", str(args.x[0]), str(args.y[0])])
输出:
args.x and args.y
[1] [8]
[1][8]
args.x[0] and args.y[0]
1 8
9
对我来说,以上是意料之外的行为.我希望 args.x 和 args.y 的值是整数,但它们是具有单个条目的列表.有人可以解释为什么会这样以及如何更改我的 add_argument
行以存储整数和/或演示 argparse
的正确用法吗?
To me the above is unexpected behaviour. I want the values of args.x and args.y to be ints, but they are lists with a single entry. Can someone explain why this is and possibly how to change my add_argument
lines to store ints and/or demonstrate proper usage of argparse
?
这个问题:Python argparse:默认参数存储为字符串,而不是列表 被标记为类似.虽然解决方案是相同的,但问题不是 - 问题是关于默认值 not 是一个列表,这里存储的值 是一个列表.在那个问题中,标题与正文提出的问题不同,因此我没有意识到我可以使用该问题的答案.我已经提交了对该问题的回答,详细说明了这一点.
This question:Python argparse: default argument stored as string, not list was flagged as similar. Although the solution is the same, the question is not - there the question was about the default value not being a list, here the stored value is a list. In that question the title does not ask the same question as the body, therefore I did not realise I could use the answer to that question. I have submitted an answer to that question elaborating on this point.
推荐答案
删除 nargs=1
部分.
来自:https://docs.python.org/3/library/argparse.html#nargs
请注意, nargs=1 会生成一个包含一项的列表.这与默认情况下不同,默认情况下,项目是由自己生产的.
Note that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.
这篇关于Python argparse 将参数存储为列表而不是整数.混淆还是正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!