为什么Python argparse中的fromfile-prefix-chars不起作用? [英] Why isn't fromfile-prefix-chars in Python argparse working?

查看:208
本文介绍了为什么Python argparse中的fromfile-prefix-chars不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中使用argparse的fromfile-prefix-chars功能从文件加载我的所有命令行参数,但是它一直抱怨我没有指定某些参数.

I'm trying to use the fromfile-prefix-chars feature of argparse in Python to load all my command line arguments from a file, but it keeps complaining that I haven't specified some argument.

代码:

import argparse

def go():
   parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
   parser.add_argument("--option1")
   parser.add_argument("--option2", type=int, required=True)
   args = parser.parse_args()

if __name__ == "__main__":
    go()

参数文件:

--option1 foo
--option2 1234

命令行和输出:

$ python testargparse.py @testargs
usage: testargparse.py [-h] [--option1 OPTION1] --option2 OPTION2
testargparse.py: error: argument --option2 is required

您可以看到我在文件中提供了必需的参数,但是argparse没有看到它.

You can see that I'm providing the required argument in the file, but argparse isn't seeing it.

推荐答案

问题在于,当在文件中指定每个参数时,每个参数与选项名称之间必须带有'='.从命令行运行(空间或=可以的地方)时,argparse在这种格式上更加灵活,但是从文件运行时,它必须具有'='.

The problem is that, when specified in a file, each argument must have an '=' between it and the option name. While argparse is somewhat more flexible on that format when run from the command line (where space or = is ok), when run from the file it must have an '='.

因此,一个有效的自变量文件将是:

So, a working argument file would be:

--option1=foo
--option2=1234

还有其他需要注意的地方,请确保行末没有多余的空格,否则当argparse读取文件时,该空格将包含在该选项中.

Something else to be aware of, be sure you don't have any extra whitespace at the end of the lines or that whitespace will get included with the option when argparse reads the file.

这篇关于为什么Python argparse中的fromfile-prefix-chars不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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