use*_*748 3 python variables argv
我需要将参数传递给我的 python 程序,例如:
py program.py var1=value var2=value var3=value var4=value
def main(*args):
variable1 = args[var1]
...
Run Code Online (Sandbox Code Playgroud)
基本上,我需要能够将参数值分配给变量,但是,用户可以按任何顺序传入参数,因此我需要确保在代码中的正确位置使用了正确的参数值。
这可能吗?如果是这样,如何?
os.environ如果您想这样做,您可以随时使用。
from os import environ
def main():
variable1 = environ.get("var1", False)
variable2 = environ.get("var2", False)
print(variable1, variable2)
main()
Run Code Online (Sandbox Code Playgroud)
然后您将var1=value1 var2=value2 python test.py传递这些值,而不是将它们作为参数传递。这会将它们设置为环境变量,并执行从 shell 环境中获取变量的程序。此代码还使用该.get()方法提供默认值(在本例中为 False),因此您可以轻松检查变量是否存在。
如果你想坚持你当前的格式,你可以使用字典来做到这一点。
假设:
传入的每个变量都将采用 format varname=value。
您知道用户应该输入什么变量名,这意味着您希望声明某些变量在您的程序中使用,并且您知道用户会给它们起什么名字。
代码基本上是这样的:
from sys import argv
def main():
#All possible variables the user could input
parameter_dict = {}
for user_input in argv[1:]: #Now we're going to iterate over argv[1:] (argv[0] is the program name)
if "=" not in user_input: #Then skip this value because it doesn't have the varname=value format
continue
varname = user_input.split("=")[0] #Get what's left of the '='
varvalue = user_input.split("=")[1] #Get what's right of the '='
parameter_dict[varname] = varvalue
#Now the dictionary has all the values passed in, and you can reference them by name, but you'll need to check if they're there.
#Then to access a variable, you do it by name on the dictionary.
#For example, to access var1, if the user defined it:
if "var1" in parameter_dict:
print("var1 was: " + parameter_dict["var1"])
else: #Or if the user did not define var1 in their list:
print("User did not give a value for var1")
main()
Run Code Online (Sandbox Code Playgroud)
测试(文件名为test.py):
$python3 test.py var2=Foo
User did not give a value for var1
$python3 test.py var1=Bar
var1 was: Olaf
$python3 test.py var7=Goose var3=Pig var1=Grape
var1 was: Grape
$python3 test.py hugo=victor var1=Napoleon figs=tasty
var1 was: Napoleon
Run Code Online (Sandbox Code Playgroud)
这样做,您还可以遍历所有用户的输入,尽管字典不保留顺序:
#Inside main() after previous items
for varname in parameter_dict:
print(varname + "=" + parameter_dict[varname])
Run Code Online (Sandbox Code Playgroud)
输出:
$python3 test.py frying=pan Panel=Executive Yoke=Oxen
User did not give a value for var1
frying=pan
Yoke=Oxen
Panel=Executive
Run Code Online (Sandbox Code Playgroud)
就个人而言,我会使用argparse.ArgumentParser. 有关详细信息,请参阅https://docs.python.org/3/library/argparse.html。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--var1', action="store");
parser.add_argument('--var2', action="store");
args = parser.parse_args();
print("var1 = %s" % args.var1);
print("var2 = %s" % args.var2);
Run Code Online (Sandbox Code Playgroud)