Passing Python variables via command line?

command-line, command-line-arguments, python

Solution

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 (i.e., 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!

Problem

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!

Original source