Grenko Grenko - 7 months ago 10
Python Question

Python: Sending a variable to another script

I'm new to python and kind of been chucked in the deep end at work.

If i had a script which has creates a list such as below:

test = 'string'

l = []

for i in test:
l.append(i)

print l


How would i send that this to another python script?

Answer

I'm assuming you want to use the variable l defined in a script called first.py into a second script called second.py

So it would be:

$ cat first.py second.py 
#first.py
def demo():
    some_list = []
    for i in 'string':
         some_list.append( i )
    return list

#second.py 
from first import demo

some_list = demo()
print some_list 

$python second.py
['s', 't', 'r', 'i', 'n', 'g']

The code in a file is declared as code module. To use it, you have to use:

from module import thing

So in this case the function demo was defined as a function in the module first

In the second file you import it and use it.

You can run arbitrary code in modules and declare variables but it is better if they are placed in functions ( or classes ) as shown above.

I hope this is what you needed.

Comments