[Tutor] Share variables between py scripts

Eric Walstad eric at ericwalstad.com
Sat Oct 7 01:25:37 CEST 2006


Bennett, Joe wrote:
> Can anyone direct me to some documentation on how to take variables from 
> one py script, execute and pass them to another script? Then I need to 
> get data back from the executed script? I've been searching Google and I 
> see information, but I am in need of some examples...
>  
>  
> Thanks!
> 
> 
> -Joe

Hi Joe,

If possible, just "run" your script (B) from within the second script 
(A).  I'd rephrase that as "in module a, import and use variables, 
functions and/or classes from module b":

##### Script B (script_b.py) #####

my_b_variable = ''

def my_b_function(var):
     return "Hello World: %s" % var

class MyBClass:
     # an empty class
     pass

#### End Script B #####

##### Script A (script_a.py) #####
from script_b import my_b_variable, my_b_function, MyBClass

def my_a_function(var):
     my_a_variable = MyBClass()
     # or
     my_a_variable = my_b_variable
     # or
     my_a_variable = my_b_function(var)
     # etc
     return my_A_variable

if __name__ == '__main__':
     # this A script is being called from the command line
     # do whatever you like in here, like run a function:
     import sys
     command_line_arg = sys.argv[1]
     print my_A_function(command_line_arg)

#### End Script A #####

$ python script_a.py foo
Hello World: foo

I hope that wasn't too remedial for you and that it's helpful.  Search 
the docs for 'functions' and 'import' for more info.

Best,

Eric.


More information about the Tutor mailing list