首页 > 解决方案 > 如何在 Python 的 Argparse 中为位置参数设置可选参数?

问题描述

我有以下代码:

# Get parsed arguments
args = argparse.ArgumentParser(description=Messages().Get(112))

# Get the arguments for sinit
args.add_argument('init', help=Messages().Get(100), action="store_true")
args.add_argument('--url', default=None, help=Messages().Get(101))

# Get the arguments for schema import
args.add_argument('schema-import', help=Messages().Get(104), action="store_true")
args.add_argument('--file', default=None, help=Messages().Get(104))

--url参数只能与init. 例如:script.py schema-import --url应该接受但应该接受。script.py schema-import --file

如何将参数设置为子参数?

标签: pythonargparse

解决方案


如前所述,可能有一种方法可以使用 argparse 执行此操作,我不确定,但无论如何我发现在应用程序逻辑中显式处理参数依赖项更加透明。这应该实现我认为你想要的:

import argparse
import sys

args = argparse.ArgumentParser(description="please only use the '--url' argument if you also use the 'init' argument")
# Going to use aliases here it's more conventional. So user can use, eg,
# -i or --init for the first argument.

args.add_argument('-i', '--init', help='init help', action="store_true")
args.add_argument('-u', '--url', default=None, help='init help')

args.add_argument('-s', '--schema-import', help='schema-import help', action="store_true")
args.add_argument('-f', '--file', help='file help')


def main():
    arguments = args.parse_args()

    if arguments.url and not arguments.init:
        # You can log an output or raise an exception if you want
        # But most likely a print statment is most appropriate
        # Since you are interacting with the CLI.
        print("You can only use the URL option with init. Exiting")
        sys.exit(0)

    print("gaurd clauses passed. Here is my code...")
    ...


if __name__ == "__main__":
    main()

测试结果(我的文件名为 temp.py):

$python temp.py -u https://www.google.com
You can only use the URL option with init. Exiting
$

$python temp.py -i -u https://www.google.com
Gaurd clauses passed. Here is my code...

推荐阅读