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

查看:15
本文介绍了如何让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 和 --bar 可能会覆盖文件中的内容).

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:
            # parse arguments in the file and store them in the target namespace
            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 中的命名空间也将包含从文件加载的任何配置,其中文件包含与命令行相同语法的参数(例如 --foo1 --bar 2).

The resulting namespace in args will then also contain any configuration that was also loaded from the file where the file contained arguments in the same syntax as on the command line (e.g. --foo 1 --bar 2).

如果您需要更复杂的解析,您也可以先单独解析文件内配置,然后有选择地选择应接管的值.例如,由于参数是按照它们指定的顺序进行评估的,因此防止文件中的配置覆盖已在命令行上显式指定的值可能是有意义的.这将允许使用默认配置文件:

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, since the arguments are evalutated in the order they are specified, it might make sense to prevent the configurations in the file from overwriting values that have been explicitly specified ont the command line. This would allow using the configuration file for defaults:

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

    # parse arguments in the file and store them in a blank namespace
    data = parser.parse_args(contents.split(), namespace=None)
    for k, v in vars(data).items():
        # set arguments in the target namespace if they haven’t been set yet
        if getattr(namespace, k, None) is not None:
            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天全站免登陆