简体   繁体   English

从命令行传递参数作为列表并解析它

[英]Pass arguments from command line as a list and parse it

I have following code:我有以下代码:

import arg
parser = arg.ArgumentParser(description="<%=@project_name%> Command Line.")
parser.add_argument(
        "--inputs", "-i", help="input files.", default="./",
    )
parser.add_argument(
        "--controls", "-c", help="Parms.", default=False
    )
parser.add_argument(
        "--outputs", "-o", help="output files.", default="./"
    )

and I run the code simply as我简单地运行代码

python code.py -i ./ -o ./ 

just wondering how can I pass a list of parameters as argument and parse through it in python?只是想知道如何将参数列表作为参数传递并在 python 中解析它? Something like:就像是:

python code.py -i ./ -o ./ -c [False, 5, 'aStr']

Quote the argument on the command line:引用命令行上的参数:

python code.py -i ./ -o ./ -c "[False, 5, 'aStr']"

Then use ast.literal_eval() to parse its value.然后使用ast.literal_eval()解析其值。

import ast
...
controls = ast.literal_eval(parser.controls)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM