Skip to content Skip to sidebar Skip to footer

Command Line Arguments As Variable Definition In Python

I'm trying to construct a (kind of template/wrapper) script, which is called with some undefined options > the_script.py --foo=23 --bar=42 --narf=fjoord which then creates a va

Solution 1:

Use this. Maybe you need some string '' brackets some where...

>>python yourfunc.py foo=4 abc=5import sys 
list=sys.argv[1:]
for i inlist:
   exec(i)

Solution 2:

This is a relatively simple task with ast.literal_eval and string splitting -- But only if you have a really well defined syntax. (e.g. only 1 of --foo=bar or --foo bar is allowed).

import argparse
import ast

parser = argparse.ArgumentParser() #allow the creation of known arguments ...

namespace,unparsed = parser.parse_known_args()

defparse_arg(arg):
    k,v = arg.split('=',1)
    try:
        v = ast.literal_eval(v) #evaluate the string as if it was a python literalexcept ValueError:          #if we fail, then we keep it as a stringpassreturn k.lstrip('-'),v

d = dict(parse_arg(arg) for arg in unparsed)
print(d)

I've put the key-value pairs in a dictionary. If you really want them as global variables, you could do globals().update(d) -- But I would seriously advise against that.

Post a Comment for "Command Line Arguments As Variable Definition In Python"