如何从主脚本修改Python子模块的argparse?

2024-04-23 21:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个自定义子模块,以便在类似的API项目中重用相同的代码。你知道吗

在我的子模块中,我有以下内容:

# sub.py
from argparse import ArgumentParser

arg_parser = ArgumentParser()
arg_parser.add_argument("-s", "--silent", help="silent mode", action="store_true")
script_args = arg_parser.parse_args()

if not script_args.silent:
    # If the silent flag isn't passed then add logging.
    #logger.addHandler(console_handler)

在我的主脚本中通过add_argument()添加额外参数的最佳方法是什么?你知道吗

# main.py
import sub

# This still works:
if sub.script_args.silent:
    # Some code

# I tried this, but it doesn't work:
sub.arg_parser.add_argument("-t", "--test", help="test mode", action="store_true")
sub.script_args.parse_args()
# The script doesn't know about -t.

Tags: 模块storepyimportaddparsermodearg
1条回答
网友
1楼 · 发布于 2024-04-23 21:34:53

您可以使用解析已知参数函数(partial parsing)。你知道吗

例如:

# sub.py
from argparse import ArgumentParser

arg_parser = ArgumentParser()
arg_parser.add_argument("-s", " silent", help="silent mode", action="store_true")
partial_script_args = arg_parser.parse_known_args()[0]

print("silent") if partial_script_args.silent else print("not silent")
# main.py
import sub

# This still works:
if sub.partial_script_args.silent:
    pass

sub.arg_parser.add_argument("-t", " test", help="test mode", action="store_true")
full_script_args = sub.arg_parser.parse_args()

print("test") if full_script_args.test else print("not test")

注意文档中的警告:

Warning:Prefix matching rules apply to parse_known_args(). The parser may consume an option even if it’s just a prefix of one of its known options, instead of leaving it in the remaining arguments list.

相关问题 更多 >