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?
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?
It depends on whether you mean sending the results of the computation to another, separately running Python process, or simply sharing that result with another component of a multi-file project.
In the former case, you'll want to use some kind of inter-process communication - some examples are writing the result to a file and reading it from the other process, establishing a socket between the two processes, or using a semaphore.
In the latter case, use Python's concept of modules to share the result of this computation with another script in your project.
I'd suggest looking at the Shelve and Pickle modules. They allow you to serialize data in a way that it can be stored between launches or shared between scripts.
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.
It is not clear whether you first script is itself running the second script, or if they are called one after the other by something external. In either case, a simple method to pass the list to the second process is via stdin, where the data itself is a pickle of the list.
For example:
script1.py:
import sys
import pickle
list = [item for item in test]
pickle.dump(list, sys.stdout)
script2.py:
import sys
import pickle
list = pickle.load(sys.stdin)
for item in list:
print item
The run: script1.py | script2.py