Reputation: 1904
I have three python files, let's call them master.py
, slave1.py
and slave2.py
. Now slave1.py
and slave2.py
do not have any functions, but are required to do two different things using the same input (say the variable inp
).
What I'd like to do is to call both the slave programs from master, and specify the one input variable inp
in master, so I don't have to do it twice. Also so I can change the outputs of both slaves in one master program etc.
I'd like to keep the code of both slave1.py
and slave2.py
separate, so I can debug them individually if required, but when I try to do
#! /usr/bin/python
# This is master.py
import slave1
import slave2
inp = #some input
both slave1
and slave2
run before I can change the input. As I understand it, the way python imports modules is to execute them first. But is there some way to delay executing them so I can specify the common input? Or any other way to specify the input for both files from one place?
EDIT: slave1
and slave2
perform two different simulations being given a particular initial condition. Since the output of the two are the same, I'd like to display them in a similar manner, as well as have control over which files to write the simulated data to. So I figured importing both of them into a master file was the easiest way to do that.
Upvotes: 0
Views: 188
Reputation: 16029
It looks like the architecture of your program is not really optimal. I think you have two files that execute immediately when you run them with python slave1.py
. That is nice for scripting, but when you import them you run in trouble as you have experienced.
Best is to wrap your code in the slave files in a function (as suggested by @sr2222) and call these explicitly from master.py
:
slave1.py/ slave2.py
def run(inp):
#your code
master.py
import slave1, slave2
inp = "foo"
slave1.run(inp)
slave2.run(inp)
If you still want to be able to run the slaves independently you could add something like this at the end:
if __name__ == "__main__":
inp = "foo"
run(inp)
Upvotes: 1
Reputation: 26160
Write the code in your slave modules as functions, import the functions, then call the functions from master
with whatever input you need. If you need to have more stateful information, consider constructing an object.
Upvotes: 1
Reputation: 89097
You can do imports at any time:
inp = #some input
import slave1
import slave2
Note that this is generally considered bad design - you would be better off making the modules contain a function, rather than just having it happen when you import the module.
Upvotes: 1