【发布时间】:2021-03-15 01:43:18
【问题描述】:
我正在使用 argparse 库来解析我的 python 脚本的参数。这是我的代码:
parser = argparse.ArgumentParser(
prog="confgit",
description="Git overhead for version control of your config files",
formatter_class=argparse.RawTextHelpFormatter, )
parser.add_argument(
"-c", "--config",
type=str,
default=DEFAULT_CONFIG_PATH,
dest="CONFIG_PATH",
help="load alternative config")
subparsers = parser.add_subparsers(help="Commands:")
subparsers.add_parser("include", help="Include file or directory in to repository").add_argument(
"file_to_include",
type=str,
action="store",
nargs="?",
const="",
default=False,
help="include file or directory in to repository")
subparsers.add_parser("exclude", help="Exclude file or directory in to repository").add_argument(
"exclude",
type=str,
action="store",
help="exclude file or directory from repository")
print(parser.parse_args())
我希望能够将不匹配任何子解析器的参数存储为字符串。例如
运行 myprogram include test.txt --config .config/cfg.txt 将导致:
Namespace(CONFIG_PATH='.config/cfg.txt', file_to_include='test.txt')
运行myprogram some text here 将导致:
Namespace(CONFIG_PATH='.config/default.txt', input="some other text")
我怎样才能做到这一点?
谢谢你的帮助
【问题讨论】:
-
通常我们将
add_subparsers结果分配给一个变量,然后将其与以下add_argument一起使用。您的链接适用于一个参数,但让这位老argparse用户感到困惑。
标签: python arguments parameter-passing argparse