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

查看:22
本文介绍了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

更多关于类型:https://docs.python.org/2/library/argparse.html#type

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

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