如何使argparse从带有选项而不是前缀的文件中读取参数 [英] how to get argparse to read arguments from a file with an option rather than prefix

查看:145
本文介绍了如何使argparse从带有选项而不是前缀的文件中读取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用python的argparse模块从命令行以及可能从文本文件中读取参数.我知道argparse的fromfile_prefix_chars,但这并不是我想要的.我想要这种行为,但是我不需要语法.我想要一个看起来像这样的界面:

I would like to know how to use python's argparse module to read arguments both from the command line and possibly from text files. I know of argparse's fromfile_prefix_chars but that's not exactly what I want. I want the behavior, but I don't want the syntax. I want an interface that looks like this:

$ python myprogram.py --foo 1 -A somefile.txt --bar 2

当argparse看到-A时,它应该停止从sys.argv或我提供的任何内容读取,并调用我编写的函数,该函数将读取somefile.text并返回参数列表.文件用完后,应继续解析sys.argv或其他内容.重要的是文件中的参数按顺序进行处理(即:-foo应该先处理,然后是文件中的参数,然后是-bar,以便文件中的参数可以覆盖--foo和-栏可能会覆盖文件中的内容).

When argparse sees -A, it should stop reading from sys.argv or whatever I give it, and call a function I write that will read somefile.text and return a list of arguments. When the file is exhausted it should resume parsing sys.argv or whatever. It's important that the processing of the arguments in the file happen in order (ie: -foo should be processed, then the arguments in the file, then -bar, so that the arguments in the file may override --foo, and --bar might override what's in the file).

这样的事情可能吗?我可以编写一个自定义函数,将新参数推送到argparse的堆栈上吗?

Is such a thing possible? Can I write a custom function that pushes new arguments onto argparse's stack, or something to that effect?

推荐答案

您可以使用自定义的 argparse.Action 打开文件,解析文件内容,然后添加参数.

You can solve this by using a custom argparse.Action that opens the file, parses the file contents and then adds the arguments then.

例如,这将是一个非常简单的操作:

For example this would be a very simple action:

class LoadFromFile (argparse.Action):
    def __call__ (self, parser, namespace, values, option_string = None):
        with values as f:
            parser.parse_args(f.read().split(), namespace)

您可以这样使用:

parser = argparse.ArgumentParser()
# other arguments
parser.add_argument('--file', type=open, action=LoadFromFile)
args = parser.parse_args()

args中的结果命名空间也将包含也从文件中加载的任何配置.

The resulting namespace in args will then also contain any configuration that was also loaded from the file.

如果需要更复杂的解析,则还可以先分别解析文件内配置,然后有选择地选择应接管的值.例如,禁止在配置文件中指定另一个文件可能是有道理的:

If you need a more sophisticated parsing, you can also parse the in-file configuration separately first and then selectively choose which values should be taken over. For example, it might make sense to disallow specifying another file in the config file:

def __call__ (self, parser, namespace, values, option_string=None):
    with values as f:
        contents = f.read()

    data = parser.parse_args(contents.split(), namespace=namespace)
    for k, v in vars(data).items():
        if v and k != option_string.lstrip('-'):
            setattr(namespace, k, v)

当然,您还可以使文件读取稍微复杂一些,例如首先从JSON读取.

Of course, you could also make the file reading a bit more complicated, for example read from JSON first.

这篇关于如何使argparse从带有选项而不是前缀的文件中读取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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