简体   繁体   English

我无法使argparse工作

[英]I can't make argparse work

I want to add arguments through append in parser.add_argument but when I run it the following message appears 我想通过parser.add_argument中的append添加参数,但是当我运行它时,出现以下消息

Prueba.py: error: argument -c1/--col1: expected one argument

Even when I tried to access help with -h it appears. 即使当我尝试使用-h访问帮助时,它也会出现。

Here's the code 这是代码

import argparse

parser = argparse.ArgumentParser(description='This is a program that makes a comparison between two files')

parser.add_argument('-c1', '--col1', action = 'append', default = [1,2], help = "Numbers in the first column")
parser.add_argument('-c2', '--col2', action = 'append', default = [1,2], help = "Numbers in the second column")

parser.add_argument('-f1', '--file1', type=str, action = 'store', help="File 1 Path")
parser.add_argument('-f2', '--file2', type=str, action = 'store', help="File 2 Path")


parser.parse_args('--col1'.split(','))
parser.parse_args('--col2'.split(','))

args = parser.parse_args()

col1 = args.col1
col2 = args.col2
file1 = args.file1
file2 = args.file2

print file1
print file2
print col1
print col2

Both --col1 and --col2 expect an associated argument. --col1--col2期望有关联的参数。 So, you are passing invalid arguments to parse_args . 因此,您正在将无效参数传递给parse_args

On top of that, your use of split(',') is an error. 最重要的是,您对split(',')是一个错误。 Surely you meant to write split() . 当然,您打算编写split() The error is benign as the code stands in the question. 由于代码代表问题,因此错误是良性的。 But as soon as you add extra arguments, it breaks down. 但是,一旦添加额外的参数,它就会崩溃。

Replace the three calls to parse_args() to be this single call: parse_args()的三个调用替换为该单个调用:

args = parser.parse_args('--col1 1 --col2 2'.split())

Here's a short demo program to demonstrate a working append argument. 这是一个简短的演示程序,用于演示有效的append参数。

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--arg', action='append')
print parser.parse_args('--arg foo --arg bar'.split())

Output 输出量

Namespace(arg=['foo', 'bar'])

It will work if you remove the lines 如果您删除行,它将起作用

parser.parse_args('--col1'.split(','))
parser.parse_args('--col2'.split(','))

What are they supposed to do anyways? 无论如何,他们应该做什么? Why are you splitting fixed strings at ',' which are not even containing any ','? 为什么要在甚至不包含任何“,”的“”处分割固定字符串?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM