如何将 python argparse 与 sys.argv 以外的 args 一起使用?

问题描述:

我已经浏览了所有文档,但似乎没有办法做到这一点,但是:

I've been all over the documentation and it seems like there's no way to do it, but:

有没有办法将 argparse 与任何字符串列表一起使用,而不仅仅是与 sys.argv 一起使用?

Is there a way to use argparse with any list of strings, instead of only with sys.argv?

这是我的问题:我有一个看起来像这样的程序:

Here's my problem: I have a program which looks something like this:

# This file is program1.py
import argparse

def main(argv):
    parser = argparse.ArgumentParser()
    # Do some argument parsing

if __name__ == '__main__':
    main(sys.argv)

当直接从命令行调用该程序时,这可以正常工作.但是,我有另一个 python 脚本,它使用不同的命令行参数运行该脚本的批处理版本,我正在使用它:

This works fine when this program is called straight from the command line. However, I have another python script which runs batch versions of this script with different commandline arguments, which I'm using like this:

import program1

arguments = ['arg1', 'arg2', 'arg3']
program1.main(arguments)

我仍然希望能够解析参数,但是 argparse 自动默认使用 sys.argv 而不是我给它的参数.有没有办法传入参数列表而不是使用 sys.argv?

I still want to be able to parse the arguments, but argparse automatically defaults to using sys.argv instead of the arguments that I give it. Is there a way to pass in the argument list instead of using sys.argv?

您可以将字符串列表传递给 parse_args:

You can pass a list of strings to parse_args:

parser.parse_args(['--foo', 'FOO'])