Reputation: 71
I have a two different python programs. How can I run one program in another when I need it (e.g if a certain condition is met)?
I heard that I can do that with import <program name>
, but when I do this, the program starts immediately and not when I need it.
Upvotes: 0
Views: 200
Reputation: 346
You should wrap the code in a function. When you want to run that part of code, just call the function.
file1.py:
def fuc1():
print("run.")
# This is to run fuc1 when you run file1 using "python file1.py"
if __name__ == '__main__':
fuc1()
in file2.py:
from file1 import fuc1
fuc1() # call it when you want to run it
Upvotes: 2
Reputation: 357
try making the second program into a function in that file and import the function like
from <file-name> import <function>
and call the function when the conditions are met
Upvotes: 1
Reputation: 346
You can just call the import wherever you need it (not necessarily at the top of the file but in the middle of your code) and wrap it inside an if statement so the import will be called when that condition is fulfilled.
Upvotes: 0