Alex Man
Alex Man

Reputation: 477

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? Something like:

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

Upvotes: 0

Views: 107

Answers (1)

Barmar
Barmar

Reputation: 780974

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.

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

Upvotes: 1

Related Questions