首页 > 解决方案 > 如何在命令行上传递参数而不在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:

标签: pythonpython-2.7command-lineargumentsargparse

解决方案


使用该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']

您可以在本教程中找到更多使用示例。


推荐阅读