[英]How to Pass variables to python script?
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 ). 实际上我已经在vB(用于GUI)中构建了一半应用程序,在python中构建了一半应用程序(用于脚本)。 I need to pass variables to python, similar, to its keywords arguments, ie, x = val1, y = val2.
我需要将变量传递给python,类似于它的关键字参数,即x = val1,y = val2。 Is there any way to achieve this?
有没有办法实现这个目标?
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
Since you're working on windows with VB, it's worth mentioning that IronPython might be one option. 由于您使用VB处理Windows,因此值得一提的是IronPython可能是一种选择。 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和IronPython都可以通过.NET进行交互,因此您可以在程序集中包装脚本并公开使用所需参数调用的函数。
Have you taken a look at the getopt module ? 你看过getopt模块了吗? It's designed to make working with command line options easier.
它旨在简化命令行选项的使用。 See also the examples at Dive Into Python .
另请参阅Dive Into Python中的示例。
If you are working with Python 2.7 (and not lower), than you can also have a look at the argparse module which should make it even easier. 如果您正在使用Python 2.7(而不是更低版本),那么您还可以查看argparse模块 ,它应该使它更容易。
If your script is not called too often, you can use a configuration file. 如果未经常调用脚本,则可以使用配置文件。
The .ini style is easily readable by ConfigParser : ConfiniParser可以轻松读取.ini样式 :
[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. 如果你有大量的变量,这可能是正确的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.