I'm new to Python (as in, yesterday), so bear with me if I don't know 'the obvious' yet.
There are two ways I could go about this, and either would work fine for me, and I'm not sure if getopt
or optparse
contains what I want/need (from what I'm reading)? I would like to do something similar to the following:
python this.py --variable VariableName="Value" -v VariableName2="Value2"
OR
python this.py --VariableName "Value"
The main issue I'm facing is that I may need to optionally pass any of the variables in, but not necessarily all and in any particular order (ergo, a raw sys.argv
won't work in my case). For some of these variables, I may be passing strings, numbers and/or arrays.
Once the variables are passed in the script, one way or another I'll need to check if they are set / not null and assign default values as necessary.
Thanks!
You definitely want a commandline argument parser. Python ships with a few. Python2.7 has argparse
which can be back-ported to earlier versions as necessary and is what I would recommend. There's also optparse
. It's not quite as nice as argparse
, but it can still do a good bit and is available with older python versions as well as newer ones.
There's also getopt
, but that one is hardly worth mentioning in comparison to the others.
I'm going to do a first and answer my own question.
As much as I like the answer @mgilson gave, I found an 'easier' way. I'm very comfortable with regular expressions, and figuring out an associative array (ie, Dictionary) isn't too difficult.
import re
args = {}
args['pythonFile'] = sys.argv[0]
for arg in sys.argv[1:]:
variable = re.search('\-\-(.*)\=',arg)
variable = variable.group(1)
value = re.search('\=(.*)',arg)
value = value.group(1)
args[variable] = value
print args
Here's the proof:
$ /opt/python27/bin/python2.7 Test.py --var1=1 --var2="Testing This"
{'var1': '1', 'pythonFile': 'Test.py', 'var2': 'Testing This'}
Woot!
I refactored the above code a little to be more flexible and modular (great solution by the way). You can now add something like --dev
instead of --dev=true
. Or you can do both. It also wont crash the app if you don't add any args.
def get_cli_args():
"""
Returns a dictionary of arguments passed to through the CLI.
"""
import re
import sys
args = {}
for arg in sys.argv[1:]:
var = re.search('\-\-([A-Za-z]*)', arg) # optional value assignment
var = var.group(1)
value = re.search('\=(.*)', arg)
value = value.group(1) if value else None
args[var] = value
return args
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.