How to Run a Python Script from Within Another Python Script

Python is a widely used general-purpose, high-level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation.

Python’s design philosophy emphasizes code readability and ease of use. It is well-suited for beginners and experienced developers alike.

While running a Python script, you may encounter a situation where you need to execute another Python script from within your current Python script.

This tutorial will guide you on how to accomplish this. It is assumed that you have basic knowledge of Python programming and you have Python installed on your system. Let’s get started!

Step 1: Write your Python Scripts

First, ensure you have two Python scripts ready. One Python script will act as the main script while the other will be invoked or called from within the main script. Let’s pretend the two scripts are “main.py” which is the main Python script, and “sub.py” which is the Python script we will be calling from “main.py”.

Step 2: Use Python’s built-in execfile() function

In older versions of Python (2.x), you can use the built-in execfile() function. The execfile() function is used to support the execution of a Python program which can either be a string or object code. Here is an example of how to use it:

Note: execfile() does not exist in Python 3.x. If you’re using Python 3.x, continue to Step 3 to learn how to import the other script as a module.

Step 3: Use Python’s built-in import statement

In Python 3, you can use the import statement to import the other script as a module. Python’s import system allows you to reference Python files as though they’re modules. Here is an example:

Note: Ensure both Python scripts are in the same directory because Python checks the current directory for any module you’re trying to import.

Step 4: Use Python’s built-in exec() function

The exec() function can be used to execute arbitrary Python code. You can read the content of “sub.py” into a string, and then pass that string to exec(). Here is an example:

Full Python Codes

Here are the full Python codes based on the methods described above:

Conclusion

This tutorial showed you different ways to run a Python script from within another Python script.

Depending on what version of Python you’re using and what your specific needs are, you can use the execfile() function, the import statement, or the exec() function.

Remember that different methods can have different implications in terms of scope and variable visibility, so choose the method that best suits your requirements.