如何将变量传递给python脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3434048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Pass variables to python script?
提问by Shubham
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed.
我知道它可以通过命令行实现,但我需要传递至少 10 个变量,命令行将意味着太多的编程,因为这些变量可能会或可能不会被传递。
Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
实际上,我已经构建了一个应用程序,一半是 vB(用于 GUI),一半是 Python(用于脚本)。我需要将变量传递给python,类似于它的关键字参数,即x = val1,y = val2。有没有办法实现这一目标?
采纳答案by Rui Vieira
回答by extraneon
Have you taken a look at the getopt module? It's designed to make working with command line options easier. See also the examples at Dive Into Python.
你有没有看过getopt 模块?它旨在使使用命令行选项更容易。另请参阅Dive Into Python 中的示例 。
If you are working with Python 2.7 (and not lower), than you can also have a look at the argparse modulewhich should make it even easier.
如果您使用的是 Python 2.7(而不是更低版本),那么您还可以查看argparse 模块,这应该使它变得更容易。
回答by schoetbi
回答by Adam Matan
If your script is not called too often, you can use a configuration file.
如果您的脚本调用频率不高,您可以使用配置文件。
The .ini style is easily readable by ConfigParser:
[Section_1]
foo1=1
foo2=2
foo3=5
...
[Section_2]
bar1=1
bar2=2
bar3=3
...
If you have a serious amount of variables, it might be the right way to go.
如果您有大量的变量,这可能是正确的方法。
回答by ars
Since you're working on windows with VB, it's worth mentioning that IronPythonmight be one option. Since both VB and IronPython can interact through .NET, you could wrap up your script in an assembly and expose a function which you call with the required arguments.
由于您正在使用 VB 处理 Windows,因此值得一提的是IronPython可能是一种选择。由于 VB 和 IronPython 都可以通过 .NET 进行交互,因此您可以将脚本包装在一个程序集中并公开一个您使用所需参数调用的函数。
回答by pyInTheSky
you can do something fun like call it as
你可以做一些有趣的事情,比如称之为
thepyscript.py "x = 12,y = 'hello world', z = 'jam'"
and inside your script,
在你的脚本中,
parse do:
解析做:
stuff = arg[1].split(',')
for item in stuff:
exec(item) #or eval(item) depending on how complex you get
#Exec can be a lot of fun :) In fact with this approach you could potentially
#send functions to your script.
#If this is more than you need, then i'd stick w/ arg/optparse

