How to Run a Python Script From Another Python Script
Python is a general purpose scripting language, containing libraries to interact with a variety of environments. Because of this, you can execute commands on your host system using the libraries included with Python. For example, you can use the "subprocess" library to make external calls to the host operating system to execute external programs. A Python script can execute another Python script through the subprocess library, or can import another Python script if you want to run the code internally.
Instructions
-
-
1
Import the subprocess module. This module contains the "call" function which allows you to call external commands to run outside the current Python code. The following example shows how to import the subprocess module to use only the "call" function:
>>>from subprocess import call
-
2
Call the external Python program using the "call" function. This function takes a list of arguments. The first argument is the command that you want to execute, and the remaining arguments list the command flags associated with that program. In this example, the "call" function only calls the Python interpreter to run an external script "example.py":
>>>retcode = call('python example.py') //"retcode" stores the return code of the script
-
-
3
Import the code for internal use. When you import the Python script you want to execute and use it internally in the current Python script, all the code in "example.py" is available for you to use as you see fit. In this case, you don't need to make external calls to other Python scripts:
import example
-
1