How to Run Another Python Script from Python Easily
You can run another Python script from your Python code using the
subprocess.run() function to execute it as a separate process, or by importing the script as a module and calling its functions directly. The subprocess method runs the script like a command, while importing lets you reuse code inside the script.Syntax
Here are two common ways to run another Python script:
- Using subprocess: Runs the script as a separate process.
- Using import: Runs the script by importing it as a module.
subprocess syntax:
subprocess.run(["python", "script_name.py"])
import syntax:
import script_name script_name.some_function()
python
import subprocess # Run script as a separate process subprocess.run(["python", "script_name.py"]) # Or import and call functions import script_name script_name.some_function()
Example
This example shows how to run a script named hello.py from another script. The hello.py script prints a greeting. The main script runs it using subprocess.run() and also imports it to call a function.
python
# hello.py def greet(): print("Hello from hello.py!") if __name__ == "__main__": greet() # main.py import subprocess import hello print("Running hello.py using subprocess:") subprocess.run(["python", "hello.py"]) print("\nCalling greet() from imported hello module:") hello.greet()
Output
Running hello.py using subprocess:
Hello from hello.py!
Calling greet() from imported hello module:
Hello from hello.py!
Common Pitfalls
1. Wrong Python executable: Use sys.executable instead of just "python" to ensure the correct Python version runs the script.
2. Importing scripts with side effects: If the script runs code on import, use if __name__ == "__main__" guard to avoid unwanted execution.
3. File paths: Make sure the script path is correct or use absolute paths to avoid "file not found" errors.
python
import subprocess import sys # Correct way to run another script with current Python subprocess.run([sys.executable, "hello.py"]) # In hello.py, protect code that runs on import if __name__ == "__main__": greet()
Quick Reference
Summary of ways to run another Python script:
| Method | Description | Use Case |
|---|---|---|
| subprocess.run() | Runs script as a separate process | When you want to run script independently and capture output |
| import module | Imports script as a module to reuse functions | When you want to call specific functions or reuse code |
| exec(open().read()) | Executes script code in current script | Less common, can cause namespace issues |
Key Takeaways
Use subprocess.run([sys.executable, 'script.py']) to run another script as a separate process safely.
Import scripts as modules to reuse functions without running the whole script.
Always protect executable code in scripts with if __name__ == '__main__' to avoid unwanted runs on import.
Check file paths and Python executable to avoid common errors.
Choose subprocess for independent runs and import for code reuse.