如何将 python argparse 与 sys.argv 以外的 args 一起使用? [英] How to use python argparse with args other than sys.argv?

查看:37
本文介绍了如何将 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'])

这篇关于如何将 python argparse 与 sys.argv 以外的 args 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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