How to Run Another Python script with Arguments in Python
Last Updated :
24 Apr, 2025
Running a Python script from another script and passing arguments allows you to modularize code and enhance reusability. This process involves using a subprocess or os module to execute the external script, and passing arguments can be achieved by appending them to the command line. In this article, we will explore different approaches to Running a Python Script From Another Script and Pass Arguments.
Run Python Script from Another Script and Pass Arguments
Below are the approaches to run a Python script from another Script and Pass Arguments
- Using the subprocess module
- Using exec
- Using the importlib module
Run Python Script From Another Script Using subprocess module
In this example, the subprocess.run function is used to execute the called_script.py script from caller_script.py. The arguments (arg1, arg2, arg3) are passed as command-line arguments when calling the script. The called script then retrieves these arguments using sys.argv and prints them.
caller_script.py
Python3
import subprocess
# Arguments to be passed to the called script
arg1 = "Geeks"
arg2 = "for"
arg3 = "Geeks"
# Run the called script with arguments
subprocess.run(['python', 'called_script.py', arg1, arg2, arg3])
called_script.py
Python3
import sys
# Retrieve arguments passed from the calling script
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
# Display the received arguments
print(f"Arguments received: {arg1}, {arg2}, {arg3}")
Run the Caller Script:
python caller_script.py
Output:
Arguments received: Geeks, for, Geeks
Run Python Script From Another Script Using exec
In this example, we use the exec function in Python that executes dynamically created Python code or scripts. We can use this method to execute a Python script within another script and pass arguments to it.
caller_script.py
Python3
# Define arguments
arg1 = "Geeks"
arg2 = "for"
arg3 = "Geeks"
# Execute called script with the arguments
exec(open("called_script.py").read(), {
'arg1': arg1, 'arg2': arg2, 'arg3': arg3})