Python argparse将参数存储为列表而不是整数.令人困惑或正确? [英] Python argparse storing arguments as lists rather than ints. Confusing or correct?

查看:69
本文介绍了Python argparse将参数存储为列表而不是整数.令人困惑或正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用两个测试脚本来教自己如何在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:默认参数存储为字符串,而不是列表被标记为相似.尽管解决方案是相同的,但问题不是-问题在于默认值不是是列表,这里的存储值是列表.在该问题中,标题提出的问题与正文提出的问题不同,因此我没有意识到我可以使用该问题的答案.关于这一点,我已经提交了对该问题的答案.

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屋!

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