How To Run Two Python Files Simultaneously

Running multiple Python files simultaneously can be quite helpful in various scenarios, such as automating tasks, running separate processes concurrently, and efficiently utilizing system resources.

In this tutorial, we’ll walk you through how to run two Python files simultaneously using different methods, including the concurrent.futures module, the threading module, and the multiprocessing module.

Step 1: Create Two Sample Python Files

Before we begin, let’s create two simple Python files that we will run simultaneously. The first file, file1.py, will compute the sum of numbers 1 to 10, and the second file, file2.py, will compute the factorial of a number (we’ll use 5 for illustration purposes). Create the files and save them with the following content:

file1.py:

file2.py:

Step 2: Run Python Files Simultaneously Using concurrent.futures

Python’s concurrent.futures module provides a high-level interface to run functions asynchronously. We’ll use the ThreadPoolExecutor class to run our Python files in parallel. Create a new Python file, main.py, and write the following code:

When you run this main.py file, it will run file1.py and file2.py simultaneously and print the output:

Sum of numbers 1-10: 55
Factorial of 5: 120

Step 3: Run Python Files Simultaneously Using threading

The threading module enables running multiple threads (smaller units of a process) concurrently in the same process. To run the Python files simultaneously using threading, modify your main.py file with the following code:

When you run the updated main.py file, it will run file1.py and file2.py simultaneously using threads.

Output:

Sum of numbers 1-10:  55
Factorial of 5:  120
Sum of numbers 1-10:  55
Factorial of 5:  120

Step 4: Run Python Files Simultaneously Using multiprocessing

The multiprocessing module is another way to run Python files simultaneously. It uses separate processes instead of threads, which can help avoid global interpreter lock (GIL) limitations. Modify your main.py file with the following code:

Output:

Sum of numbers 1-10:  55
Factorial of 5:  120
Sum of numbers 1-10:  55
Factorial of 5:  120
Sum of numbers 1-10:  55
Sum of numbers 1-10:  55
Factorial of 5:  120
Factorial of 5:  120
Sum of numbers 1-10:  55
Factorial of 5:  120

When you run the updated main.py file, it will run file1.py and file2.py simultaneously using separate processes.

Conclusion

In this tutorial, we have covered three different methods to run two Python files simultaneously using the concurrent.futures, threading, and multiprocessing modules.

Each method has its advantages and limitations, so choose the one that best fits your use case and system requirements. Now you know how to run multiple Python files concurrently to enhance the efficiency of your code.