Skip to content

How can I make one python file run another?

To run one Python file from another, you can use the exec function or the subprocess module. (Note: For reusable code, the standard import statement is generally preferred.)

Here's an example using the exec function:

Run a python file from inside another Python file using the exec function

python
# main.py

with open("other.py") as f:
    exec(f.read())

This will execute the code in other.py as if it were written in the main.py file. Note that exec() runs the code in the current namespace and is generally discouraged for external scripts due to security risks and potential variable conflicts.

Here's an example using the subprocess module:

Run a python file from inside another Python file using the subprocess module

python
import subprocess

# Run the other script
subprocess.run(["python", "other.py"], check=True)

This will run the other.py script as a separate process. The check=True argument ensures a CalledProcessError is raised if the script exits with a non-zero status.

Note that these methods will only work if the script you want to run is in the same directory as the script that is running it. If the script is in a different location, you will need to provide the full path to the script file.

For example:

Provide the full path and run a python file from another

python
# main.py

with open(r"C:\scripts\other.py") as f:
    exec(f.read())

Provide the full path and run a python file from another by subprocess module

python
import subprocess

# Run the other script
subprocess.run(["python", r"C:\scripts\other.py"], check=True)

If you frequently run scripts located outside the current working directory, you can also add their directory to sys.path before importing, or use absolute paths as shown above.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.