Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass variables to python script?

Tags:

python

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

like image 637
Shubham Avatar asked Aug 08 '10 11:08

Shubham


People also ask

How do you pass a parameter to a function in Python?

Here are simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.


3 Answers

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.

like image 99
Rui Vieira Avatar answered Nov 15 '22 04:11

Rui Vieira


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
like image 27
pyInTheSky Avatar answered Nov 15 '22 05:11

pyInTheSky


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.

like image 35
ars Avatar answered Nov 15 '22 05:11

ars