python - 如何在 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
如何将参数设置为子参数?
解决方案
如前所述,可能有一种方法可以使用 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...
推荐阅读
- vue.js - 如何为 IE11 添加对 vue-apollo 的支持?
- reactjs - 构建作业拉取 repo,然后开始构建映像,但耗时太长或以失败告终
- c# - 如何通过复杂子句列表创建where?
- laravel - 通过 artisan 和 composer 安装的区别
- r - 何在 R 中使用带有 tm 包的自定义词干算法?
- selenium - 与 Implicitwait 相比,我们是否需要为 ExplicitWait 声明更少的时间
- .net - Couchbase Mobile Client Lite 如何通过代理
- python - Django:如何通过模型方法设置默认字段值
- javascript - 为什么日历多个课程缺少右下角的蓝色三角形?
- supervisord - Supervisord:不要从 crond 杀死进程