Reputation: 11
I am pretty new to programming with python. So apologies in advance: I have two python scripts which should share variables. Furthermore the first script (first.py) should call second script (second.py)
first.py:
import commands
x=5
print x
cmd = "path-to-second/second.py"
ou = commands.getoutput(cmd)
print x
second.py looks like this
print x
x=10
print x
I would expect the output: 5 5 10 10
In principle I need a way to communicate between the two scripts. Any solution which does this job is perfectly fine.
Thank you for your help!
Tim
Upvotes: 1
Views: 133
Reputation: 177
In your second.py, you'll want these lines
from sys import argv
x = argv[1] #Second argument (starts at 0, which is the script name)
Then your first.py should execute second.py such as
import os
os.system("python second.py " + x)
Upvotes: 1
Reputation: 193
Each python script has its own root scope, and in this case you're launching another entirely separate process, so its x
is completely different from the other script's x
, otherwise each python script would have to have unique variable names to avoid collision.
What you probably want to do is provide the values needed by second.py
on the command line. Here's a simple way to do that:
first.py:
import commands
x=5
print x
cmd = "path-to-second/second.py " + str(x)
ou = commands.getoutput(cmd)
second.py:
import sys
x = int(sys.argv[1]) # sys.argv[0] is "second.py"
print x
x=10
print x
Upvotes: 1