Run One Python Script From Another in Python

Below are some of the ways by which we can make one Python file run another in Python:

Make One Python File Run Another Using import Module

In this example, file_2.py imports functions from file_1.py using the import statement. By calling the imported function in file_2.py (file_1.printing()), the code executes the printing() function defined in file_1.py, allowing for the integration and execution of code from one file within another.

Python3




# file_1.py
 
# creating function
def printing():
    print("Hello world!")


Python3




# file_2.py
 
# importing file_1
import file_1
 
# calling function of file_1.py form file_2.py
file_1.printing()


Output:

Run One Python Script From Another Using exec() Function

In this example, file_2.py opens and reads the file_1.py, by ‘with‘ statement using the ‘open‘ function it opens file_1.py, and the ‘read‘ function reads the file_1.py. The code read from file_1.py will be executed by using the exec() function within file_2.py.

Python3




# file_1.py
 
# printing hello world!
print("Hello world!")


Python3




# file_2.py
 
# opening file_1.py and reading it with read() and executing if with exec()
with open("file_1.py") as file:
    exec(file.read())


Output:

Python Run One Script From Another Using subprocess Module

In this example, file_2.py imports the subprocess module using the import statement. By using run() function Python script in “file_1.py” will be executed as a separate process within file_2.py.

Python3




# file_1.py
 
# printing This is file_1 content.
print("This is file_1 content.")


Python3




# file_2.py
 
# importing subprocess module
import subprocess
 
# running other file using run()
subprocess.run(["python", "file_1.py"])


Output:

Run One Python Script From Another Using os.system() Function

In this example, file_2.py imports the os module using the import statement. Then using os.system() to execute the command “python file_1.py” and file_1.py will run within the same process but in a separate system shell.

Python3




# file_1.py
 
# printing This is file_1 content.
print("This is file_1 content.")


Python3




# file_2.py
 
# importing os module
import os
 
# running other file using run()
os.system("python file_1.py")


Output:

Run One Python Script From Another in Python

In Python, we can run one file from another using the import statement for integrating functions or modules, exec() function for dynamic code execution, subprocess module for running a script as a separate process, or os.system() function for executing a command to run another Python file within the same process. In this article, we will explore all the specified approaches to make one Python file run another.

Similar Reads

Run One Python Script From Another in Python

Below are some of the ways by which we can make one Python file run another in Python:...

Conclusion

...