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 variable called foo=23, bar=42, narf='fjoord' inside it.
What's the way to do it? I tried with getopt, but it needs a second parameter, so I have to define which options to get and of course, I want to be able to define my variable names via command line. I tried OptionParser too, not sure how to deal with undefined options though.
So is the way manually parsing the sys.argv, or is there maybe a module out there, which does exactly the same thing?
解决方案
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()
def parse_arg(arg):
k,v = arg.split('=',1)
try:
v = ast.literal_eval(v) #evaluate the string as if it was a python literal
except ValueError: #if we fail, then we keep it as a string
pass
return 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.