python - 如何在命令行上传递参数而不在python中使用标志
问题描述
所以我有我的 main.py 脚本,它基本上将根据命令行上传递的内容运行某些条件语句。例如,如果我使用main.py -t
,这将运行测试模式。如果我运行main.py -j /testdata -c 2222-22-22 -p 2222-22-22
这将运行默认模式等等。
如何停止在命令行上传递标志并能够运行我的代码,而不是使用标志 -j , -c 和 -p ,我可以正常传递值。
到目前为止,我的代码如下:
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--execute-cur-date", action="store", required=False)
parser.add_argument("-p", "--execute-pre-date", action="store", required=False)
parser.add_argument("-j", "--execute-json-path", action="store", required=False)
parser.add_argument("-t", "--execute-test", action="store_true", required=False)
args = parser.parse_args()
if args.execute_test:
testing()
elif args.execute_json_path and args.execute_cur_date and args.execute_pre_date:
解决方案
使用该sys
模块解析命令行参数(sys.argv 将是参数列表):
#!/usr/bin/env python3
import sys
# The first argument (sys.argv[0]) is the script name
print('Command line arguments:', str(sys.argv))
运行脚本:
$ python3 script.py these are my arguments
Command line arguments: ['script.py', 'these', 'are', 'my', 'arguments']
您可以在本教程中找到更多使用示例。
推荐阅读
- java - Hibernate/JPA 的新功能:对表主键进行 java.lang.NullPointerException 过滤
- c# - 将新的 VISA 网络设备添加到资源
- prestashop - 模块 Prestashop 1.7:自定义图片上传总是被替换
- jenkins - gitversion 在 windows 上的报告与在 mac 上不同。为什么?
- excel - 在 VBA 代码中计算数组的 IRR
- jenkins - Jenkins slave 中的问题无法连接 Jenkins
- laravel - Laravel Mix (v6.16.0) 忽略 tailwind.config.js (v1.2.0) 设置
- android - React natives LINKING 组件在调试中工作正常,但在 android 版本中没有响应
- javascript - 如何从单个查询中的所有嵌套/链接文档中获取内容到 Prismic?
- javascript - 从 Google Sheets html 模板运行时,工作测试的 javascript 不起作用