Open In App

How Can I Make One Python File Run Another File?

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python programming, there often arises the need to execute one Python file from within another. This could be for modularity, reusability, or simply for the sake of organization. In this article, we will explore different approaches to achieve this task, each with its advantages and use cases.

Making One Python File Run Another File in Python

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

  1. Using import Statement
  2. Using exec() Function
  3. Using Subprocess Module

target_file.py

This is the file that we are using in our article to run another Python file. In this code, we are just printing some statements that we will fetch in another file by using different approaches.

Python3
def some_function():
    print("Hello GeeksforGeeks from target_file.py")

Using import Statement

The most straightforward way to run a Python file from another is by using the import statement. This approach treats the target file as a module, allowing you to call its functions, access its variables, and execute its code.

main.py

In this example, we are using an import statement to import the target_file.py file and use some_function() by calling it in another file.

Python3
import target_file

target_file.some_function()

Output:

Run main.py file and you will see the following as output.

Hello GeeksforGeeks from target_file.py

Using exec() Function

The exec() function in Python allows you to execute dynamically generated Python code. This can be used to run the contents of a file within another file.

app.py

In this example, `main.py` reads the contents of `external_code.py` as a string using the `open()` function. It then passes this string to the `exec()` function, which executes the code. This approach is flexible but should be used with caution as it can execute arbitrary code and may pose security risks.

Python3
with open('target_file.py', 'r') as file:
    code = file.read()
    exec(code)

Output:

Run app.py file and you will see the following as output.

Hello GeeksforGeeks from target_file.py

Using Subprocess Module

Another approach is to use the subprocess module, which allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

sub.py

In this example, the subprocess module is used to spawn a new process running the Python interpreter, executing the target_file.py script.

Python3
import subprocess

subprocess.call(['python', 'target_file.py'])

Output:

Run sub.py file and you will see the following as output.

Hello GeeksforGeeks from target_file.py

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads