Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Python variables via command line?

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!

like image 530
Jonathan Avatar asked Jan 16 '23 01:01

Jonathan


1 Answers

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.

like image 56
mgilson Avatar answered Jan 20 '23 02:01

mgilson