. Advertisement .
..3..
. Advertisement .
..4..
Python is a powerful programming language that makes it easy for a software developer to build a wide range of applications. The Python language is easy to learn and has a clean syntax. This has enabled it to become one of the most in-demand programming languages in the world. In this blog, we will look at some tips on using Python to run another Python script.
How To Use Python To Run another Python script?
Approach 1: Utilize this technique
You can utilize this technique for using Python to run another Python script. It’s incredibly simple to utilize. Let’s take a look at an instance of this:
def func1():
print ("i'm in function")
if __name__ == '__main__':
func1()
Result:
i'm in function
Next,
import subprocess
subprocess.call("Script1.py", shell=True)
Therefore, you can use this way to run another script.
Approach 2: Use the execfile()
The desired file is run in the interpreter via the execfile() function. Only Python 2 supports this function. The execfile() function was dropped in Python 3, although the exec() method still works to do the same task.
The execfile() function is used in the code that follows to run one Python script inside another Python script.
Script2.py:
# Python 2 code
execfile("Script1.py")
Output:
Function 1 is active
In Python 3, you can execute the same thing by using:
Script2.py:
exec(open("Script1.py").read())
Output:
Function 1 is active
Approach 3: Use the subprocess()
Another solution for using Python to run another Python script is utilizing subprocess().
The subprocess module has the ability to launch additional processes and receive their outputs as well. This brand-new module is meant to take the place of a number of more outdated ones, as os.system, which was previously used to execute a Python script inside of another Python script.
Look at the following example to understand more about this method.
Script1.py:
def func1():
print ("Function 1 is active")
if __name__ == '__main__':
# Script2.py executed as script
# do something
func1()
Script2.py:
import subprocess
subprocess.call("Script1.py", shell=True)
Output
Function 1 is active
Conclusion
Using Python to run another Python script is a confusing problem. We hope this blog has helped clear the air around how to do it. If you have more questions about this topic, please leave a comment below. Thank you for reading, we are always excited when one of our posts can provide useful information on a topic like this!
Read more
Leave a comment