简体   繁体   中英

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.

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, ie, x = val1, y = val2. Is there any way to achieve this?

If you are using Python <2.7 I would suggest optparse . optparse is deprecated though, and in 2.7 you should use argparse

It makes passing named parameters a breeze.

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. 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.

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 .

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.

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.

What do you think about creating a python script setting these variables from the gui side? When starting the python app you just start this script and you have your vars.

Execfile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM