0

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.

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Please note that <file-name> goes without the .py and must be accessible from executing directory.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.