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

查看:20
本文介绍了为什么 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天全站免登陆