[英]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. 我是Python的新手(就像昨天一样),如果我不知道“显而易见的”,请耐心等待。
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)? 有两种方法可以解决这个问题,对我来说哪一种都可以正常工作,而且我不确定
getopt
或optparse
包含我想要/需要的东西(从我正在阅读的内容)? 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). 我面临的主要问题是我可能需要可选地传递任何变量,但不一定是所有变量和任何特定顺序(ergo,原始
sys.argv
在我的情况下不起作用)。 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.
Python附带了一些。 Python2.7 has
argparse
which can be back-ported to earlier versions as necessary and is what I would recommend. Python2.7有
argparse
,可以根据需要反向移植到早期版本,这是我推荐的。 There's also optparse
. 还有
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
那么好,但它仍然可以做得很好,并且可用于较旧的python版本以及较新的版本。
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. 尽管我喜欢@mgilson给出的答案,但我发现了一种“更容易”的方式。 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
. 您现在可以添加类似
--dev
而不是--dev=true
。 Or you can do both. 或者你可以做到这两点。 It also wont crash the app if you don't add any args.
如果你不添加任何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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.