argparse中如何搭配可选位置参数使用子命令
解决方案
不用搞复杂的子命令配置,直接调整argparse的参数规则就能实现需求,核心改动如下:
- 把
--display从需要传字符串值的参数改成布尔开关:用action='store_true'配置后,命令行写--display时不需要跟任何值,参数会自动标记为True,没传的话默认是False - 加一层参数校验:如果检测到用户传了
--display但没传--input,直接抛出参数错误,强制要求两个参数搭配使用 - 调整原有的判断逻辑,适配布尔值的判断规则,把打开网页的逻辑放到
--input的匹配分支里,逻辑更严谨
修改后可直接运行的代码
# main.py import os, numpy import argparse import webbrowser new = 2 def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, help='Choose input') # 调整--display为无值布尔开关 parser.add_argument('-d', '--display', dest='disp', action='store_true', help='Open webpage when used with --input', default=False) args = parser.parse_args() # 校验参数从属关系 if args.disp and not args.input: parser.error("--display 必须配合 --input 参数使用") if args.input == 'infile': print('This is input file') if args.disp: url = "https://stackoverflow.com/" webbrowser.open(url, new=new, autoraise=True) if __name__ == '__main__': main()
测试效果
- 运行
python3 main.py --input infile --display:控制台输出This is input file,同时自动拉起浏览器打开指定网页,完全符合预期 - 运行
python3 main.py --input infile:仅打印This is input file,不会触发网页打开逻辑 - 单独运行
python3 main.py --display:程序直接抛出参数错误,禁止脱离--input单独使用--display,满足参数从属要求
内容的提问来源于stack exchange,提问作者newstudent
相关产品推荐
相关产品推荐

