2

I have two Python scripts in two different locations and cannot be moved. What is the best way to send information between the two scripts?

say for example in script1.py i had a string e.g.

x = 'teststring'

then i need variable 'x' passed to script2.py, which saves the variable 'x' to a text file?

Any ideas?

Peter
  • 23
  • 2

3 Answers3

3

You just import it.

#script2.py
from script1 import x

To make the script2 find the script1, the script1 file must be in the module search path

edit

Here's an example:

First we create a dir and display the value of the module search path:

$mkdir some_dir
$echo $PYTHONPATH

It's nothig. Then we create a file with the variable x initialized to "hola" in that directory:

$cat >some_dir/module_a.py <<.
> x = "hola"
> .

And we create another python file to use it:

$cat >module_b.py<<.
> from module_a import x
> print x
> .

If we run that second script we got an error:

$python module_b.py 
Traceback (most recent call last):
  File "module_b.py", line 1, in <module>
    from module_a import x
ImportError: No module named module_a

But, if we specify the some_dir in the module search path, and run it again, should work:

$export PYTHONPATH=some_dir
$python module_b.py 
 hola
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • would that work even though the scripts are in two different locations? – Peter Jun 18 '10 at 03:00
  • @Peter :) I knew that would be the next question, I was looking the reference. I have updated the answer. For a ( bit ) more complete sample see : http://stackoverflow.com/questions/3066126/python-sending-a-variable-to-another-script/3066158#3066158 – OscarRyz Jun 18 '10 at 03:00
  • Instead of modifying PYTHONPATH, you might want instead to append the path to some_dir in sys.path, in the program that needs to use the other file. This would have the advantage of not modifying PYTHONPATH just for a single project. – Eric O. Lebigot Jun 18 '10 at 10:06
0

How about using a socket?

This is a good tutorial about network programming in Python. It includes client/server sample scripts:

http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf

Alejandro
  • 1,002
  • 8
  • 14
0

Here is the standard way of doing what you want:

import sys
sys.path.append('/path/to/the_other_module_dir')
import script1

print script1.x

In fact, if you modify the environment variable PYTHONPATH for each single project that involves modules that are not in the same directory, you'll have an unnecessarily long PYTHONPATH variable and users of your script will also have to modify their PYTHONPATH. The above canonical method solves these problems.

Alternatively, you might want to directly import x:

from script1 import x
print x
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260