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?
-
What do you mean by "different locations" ?Steven D. Majewski– Steven D. Majewski2010年06月18日 03:13:54 +00:00Commented Jun 18, 2010 at 3:13
3 Answers 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
3 Comments
How about using a socket?
This is a good tutorial about network programming in Python. It includes client/server sample scripts:
Comments
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