Passing Python variables via command line?

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:


getopt


optparse


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.


sys.argv



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!




3 Answers
3



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.


argparse


optparse


argparse



There's also getopt, but that one is hardly worth mentioning in comparison to the others.


getopt



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!






Although this sounds very clever (indeed), perhaps it's not the most "pythonic" way to achieve what you really want, from what I've seen around. But don't worry, you'll soon absorb python's characteristics and use them naturally the more you use them.

– heltonbiker
Nov 13 '12 at 18:53






Ha, thanks, and I was fairly certain that was the case when I wrote it. Eventually though, as I learn more I'll improve, but right now for any beginner at my level might benefit from this.

– Jonathan
Nov 13 '12 at 18:58






The right balance between learn-first-then-do or do-whatever-works-right-now depends on the balance between the need to solve the problem vs. the need to learn the tool. But I guess this applies for every problem-tool relationship... (depth-first-searching can be paralyzing...)

– heltonbiker
Nov 14 '12 at 1:24



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.


--dev


--dev=true


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



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ