argparse Python 2.7中一个参数的多个文件 [英] Multiple files for one argument in argparse Python 2.7

查看:317
本文介绍了argparse Python 2.7中一个参数的多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在argparse中创建一个参数,以便可以输入多个可以读取的文件名. 在此示例中,我只是尝试打印每个文件对象以确保其正常工作,但出现错误:

Trying to make an argument in argparse where one can input several file names that can be read. In this example, i'm just trying to print each of the file objects to make sure it's working correctly but I get the error:

error: unrecognized arguments: f2.txt f3.txt

.我怎样才能认出所有人?

我在终端中的命令来运行程序并读取多个文件

my command in the terminal to run a program and read multiple files

python program.py f1.txt f2.txt f3.txt

Python脚本

import argparse

def main():
    parser = argparse.ArgumentParser()      
    parser.add_argument('file', nargs='?', type=file)
    args = parser.parse_args()

    for f in args.file:
        print f

if __name__ == '__main__':
    main()

我使用了nargs='?' b/c,我希望它可以是可以使用的任意数量的文件.如果我将add_argument更改为:

I used nargs='?' b/c I want it to be any number of files that can be used . If I change add_argument to:

parser.add_argument('file', nargs=3)

然后我可以将它们打印为字符串,但无法使其与'?'一起使用

then I can print them as strings but I can't get it to work with '?'

推荐答案

如果您的目标是读取一个或多个可读文件,则可以尝试以下操作:

If your goal is to read one or more readable files, you can try this:

parser.add_argument('file', type=argparse.FileType('r'), nargs='+')

nargs='+'将所有命令行参数收集到一个列表中.还必须有一个或多个参数,否则将生成错误消息.

nargs='+' gathers all command line arguments into a list. There must also be one or more arguments or an error message will be generated.

type=argparse.FileType('r')尝试将每个参数作为文件打开以供读取.如果argparse无法打开文件,它将生成一条错误消息.您可以使用它来检查参数是否为有效且可读的文件.

type=argparse.FileType('r') tries to open each argument as a file for reading. It will generate an error message if argparse cannot open the file. You can use this for checking whether the argument is a valid and readable file.

或者,如果您的目标是读取零个或更多可读文件,则可以简单地将nargs='+'替换为nargs='*'.如果没有提供命令行参数,这将为您提供一个空列表.如果没有任何文件,也许您可​​能想打开stdin-如果是这样,只需将default=[sys.stdin]作为参数添加到add_argument.

Alternatively, if your goal is to read zero or more readable files, you can simply replace nargs='+' with nargs='*'. This will give you an empty list if no command line arguments are supplied. Maybe you might want to open stdin if you're not given any files - if so just add default=[sys.stdin] as a parameter to add_argument.

然后处理列表中的文件:

And then to process the files in the list:

args = parser.parse_args()
for f in args.file:
    for line in f:
        # process file...


有关nargs的更多信息: https://docs.python.org/2/library/argparse.html#nargs


More about nargs: https://docs.python.org/2/library/argparse.html#nargs

有关类型的更多信息: https://docs.python.org/2/library/argparse.html#type

More about type: https://docs.python.org/2/library/argparse.html#type

这篇关于argparse Python 2.7中一个参数的多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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