Execute Python Files in Batches: A Guide

There are several ways to batch execute multiple Python files, and one method is as follows:

  1. The primary file is ‘main.py’.
  2. subroutine
import subprocess

# 定义要执行的Python文件列表
file_list = ['file1.py', 'file2.py', 'file3.py']

# 循环执行每个Python文件
for file in file_list:
    subprocess.run(['python', file])

In the example above, file_list is the list of Python files to be executed, and you can add or remove file names as needed. Then use the subprocess.run() function to execute each file.

  1. Use command-line tools to execute multiple Python files in bulk.

In the command line, you can use a for loop combined with Python commands to bulk execute multiple Python files, for example:

for /r %F in (*.py) do python %F

This command will execute all .py files in the current directory and its subdirectories. You can modify the file filtering criteria and the execution command as needed.

There are two common methods for bulk executing multiple Python files, choose the one that is suitable for your situation.

bannerAds