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.
Here's an example using the exec
function:
# 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.
Here's an example using the subprocess
module:
import subprocess
# Run the other script
subprocess.run(["python", "other.py"])
This will run the other.py
script as a separate process.
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:
# main.py
with open("C:\scripts\other.py") as f:
exec(f.read())
import subprocess
# Run the other script
subprocess.run(["python", "C:\scripts\other.py"])