- How can I make one python file run another?
- Related Resources
- Python Run Another Python Script
- Use the import Statement to Run a Python Script in Another Python Script
- Use the execfile() Method to Run a Python Script in Another Python Script
- Run Python script from another script & pass arguments
- Method 1 : Importing in other script
- Frequently Asked:
- Method 2 : Using os.system and sys.argv
- Method 3 : Using subprocess module
- SUMMARY
- Related posts:
- How to Run One Python Script From Another
- Steps to Run One Python Script From Another
- Step 1: Place the Python Scripts in the Same Folder
- Step 2: Add the Syntax
- Step 3: Run One Python Script From Another
- Call a Specific Variable from One Python Script to Another
- Interaction of Variables from the Two Scripts
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.
# 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"])
Related Resources
Python Run Another Python Script
- Use the import Statement to Run a Python Script in Another Python Script
- Use the execfile() Method to Run a Python Script in Another Python Script
- Use the subprocess Module to Run a Python Script in Another Python Script
A basic text file containing Python code that is intended to be directly executed by the client is typically called a script, formally known as a top-level program file.
Scripts are meant to be directly executed in Python. Learning to run scripts and code is a fundamental skill to learn in the world of python programming. Python script usually has the extension ‘.py’ . If the script is run on a windows machine, it might have an extension, .pyw .
This tutorial will discuss different methods to run a Python script inside another Python script.
Use the import Statement to Run a Python Script in Another Python Script
The import statement is used to import several modules to the Python code. It is used to get access to a particular code from a module. This method uses the import statement to import the script in the Python code and uses it as a module. Modules can be defined as a file that contains Python definitions and statements.
def func1(): print ("Function 1 is active") if __name__ == '__main__': # Script2.py executed as script # do something func1()
import Script1.py def func2(): print("Function 2 is active") if __name__ == '__main__': # Script2.py executed as script # do something func2() Script1.func1()
Function 2 is active Function 1 is active
Use the execfile() Method to Run a Python Script in Another Python Script
Run Python script from another script & pass arguments
In Python programming we often have multiple scripts with multiple functions. What if, if some important and repeated function is in another script and we need to import and run to our main script. So, here in this article we will learn about several methods using which you can Run a Python script from another Python script and pass arguments.
Table Of Contents
Method 1 : Importing in other script
First method we will be using is very simple and easiest one. In this method we can just import the function and then call the function by just passing the arguments. Must keep in mind that both the files should reside in the same folder.
See the example code below
Frequently Asked:
# *args has been used to pass variable number of positional arguments. def expenseCalculator(*expense): # sum adds the numbers provided as parameters. print('Previous month expense was ',sum(expense))
# importing the function from another module. from code_1 import expenseCalculator # calling the function and by passing arguments. expenseCalculator(2000,3000)
Previous month expense was 5000
So, In the above code and output you can see we have two files code_1.py and script.py. In code_1.py we have a function which takes positional arguments and returns the sum by using the sum() method. This function has been imported in the script.py. When this function is called in the script.py by providing some arguments, the function executes and returns the sum of the arguments provided.
Method 2 : Using os.system and sys.argv
Next method we can use to Run a Python script from another Python script and pass arguments is a combination of two methods first is system() of os module and another is argv() from sys module. Let’s look both of these methods one by one.
os.system : os module comes bundled with python programming language and is used to interact with system or give system commands to our Operating System. system() method is used to execute system commands in a subshell.
sys.argv : This module in python programming language is widely used to interact with the system it provides various function and modules that can communicate with the Python Interpreter and also used to manipulate python runtime environment. sys.argv reads the arguments which are passed to the Python at the time of execution of the code. Arguments provided to the sys.argv is stored in list, first index which is index number 0 is reserved for the file name and then arguments are stored.
Now see the example code below and then we will discuss more about this method.
# importing sys module import sys # *args has been used to pass variable number of positional arguments. def expenseCalculator(*expense): # sum adds the numbers provided as parameters. print('Previous month expense was ',sum(expense)) # storing the arguments by slicing out the 0 index which holds the file name. arguments = sys.argv[1:] # initialized an empty list. expenses = [] # looping through the arguments to convert it into int. for i in arguments: expenses.append(int(i)) # calling the function and passing the expenses. expenseCalculator(*expenses)
# importing the os module. import os # running the file code_1.py and passing some arguments. os.system("python3 code_1.py 2000 3000 5000")
Previous month expense was 10000
So, In the code and output above you can see we have two files code_1.py which has function expenseCalculator() which takes the variable number of positional arguments and returns the sum of all the expenses using the sum() function. Also we have sys.argv() file which reads all the arguments which are provided at the time of execution and then using int() function we have converted the arguments which are in string to integer.
Then there is script.py from where we are running another script which is code_1.py. In this file, we have used os.system() to run the code_1.py and also provided some arguments.
So, you can see we have used sys.argv() to read all the arguments which are passed at the time of execution and used os.system() to execute the program with some arguments.
Method 3 : Using subprocess module
Another method we can use to Run a Python script from another Python script and pass arguments is a combination of Popen() and argv() methods.
The Popen() method is of subprocess module which comes pre-installed with Python programming language and is mostly used to execute system commands. It has some features which provide edge over the os module like, this connects to input/output/error pipes and obtains their return codes. This also allows spawning new process. The Popen() method is used to execute system commands via string arguments/commands.
Now See the Example codes below
# importing sys module import sys # *args has been used to pass variable number of positional arguments. def expenseCalculator(*expense): # sum adds the numbers provided as parameters. print('Previous month expense was ',sum(expense)) # storing the arguments by slicing out the 0 index which holds the file name. arguments = sys.argv[1:] # initialized an empty list. expenses = [] # looping throught the arguments to convert it into int. for i in arguments: expenses.append(int(i)) # calling the function and passing the expenses. expenseCalculator(*expenses)
# importing subprocess module import subprocess # using Popen() method to execute with some arguments. subprocess.Popen("python3 code_1.py 2000 3000 4000",shell=True)
Previous month expense was 9000
So, In the code and output above you can see we have used Popen() method to run a python script and argv() to read arguments. The code_1.py file is same as the method 2 but in script.py file instead of system() we have used Popen() to pass arguments. The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.
SUMMARY
So In this Python tutorial article we learned about several methods using which we can Run a Python script from another Python script and pass arguments. We learned about sys.argv() using which which we can read the arguments passed at the time of execution in the command prompt. Also we learned about two other methods Popen() of subprocess module and system() of os module using which we can execute the system commands or here we have used to run the Python script from another Python script and also passed some arguments at the time of execution.
You can always use any of the methods above, but most easy to understand and implement is the first method. Make sure to read and write example codes in order to have a better understanding of this problem.
Related posts:
How to Run One Python Script From Another
In this short guide, you’ll see how to run one Python script from another Python script.
More specifically, you’ll see the steps to:
- Run one Python script from another
- Call a specific variable from one Python script to another
But before we begin, here is a simple template that you may use to run one Python script from another (for Python scripts that are stored in the same folder):
import script_name_to_call
Steps to Run One Python Script From Another
Step 1: Place the Python Scripts in the Same Folder
To start, place your Python scripts in the same folder.
For example, let’s suppose that two Python scripts (called python_1 and python_2) are stored in the same folder:
The ultimate goal is to run the python_2 script from the python_1 script.
Step 2: Add the Syntax
Next, add the syntax to each of your scripts.
For instance, let’s add the following syntax in the python_1 script:
import python_2 print('what are you up to?')
- The first line of ‘import python_2’ in the python_1 script, would call the second python_2 script
- The second line of the code simply prints the expression of ‘what are you up to?’
Now let’s add the syntax in the python_2 script:
In this case, the expression of ‘hello world’ would be printed when running the second script.
Note that you must first save the syntax that was captured in the python_2 script before calling it from another script.
Step 3: Run One Python Script From Another
Now you’ll need to run the script from the python_1 box in order to call the second script.
Notice that the results of the python_2 script would be displayed first, and only then the results of the python_1 script would be displayed:
hello world what are you up to?
Call a Specific Variable from One Python Script to Another
Let’s now see how to call a specific variable (which we will call ‘x’) from the python_2 script into the python_1 script.
In that case, you’ll need to edit the syntax in the python_1 script to the following:
import python_2 as p2 print(p2.x)
Next, assign a value (e.g., ‘hello world’) to the ‘x’ variable in the python_2 script:
Don’t forget to save the changes in the python_2 script.
Finally, run the syntax from the python_1 script, and the ‘hello world’ expression would be printed:
Interaction of Variables from the Two Scripts
In the final section of this guide, you’ll see how variables from the two scripts may interact.
For example, let’s suppose that the python_1 script has the variable of y = 2, while the python_2 script has the variable of x = 5. The goal is to sum those two variables and display the results.
First, modify the syntax in the python_1 script to the following:
import python_2 as p2 y = 2 print(p2.x + y)
Then, change the syntax in the python_2 script to:
As before, don’t forget to save the changes in the python_2 script.
Finally, run the syntax from the python_1 script, and you’ll get ‘7’ which is indeed the sum of the two variables: