h4cktivist
h4cktivist

Reputation: 71

How can I run a python program in another python program?

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

Answers (3)

Yi Zhao
Yi Zhao

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

Lavanya V
Lavanya V

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

Amit Davidson
Amit Davidson

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

Related Questions