Several ways to run python files (bat files) in multiple threads

After writing multiple automated reports, it will be cumbersome to run the python files one by one each time. The best way this time is to write another python file to manage these automated reports in a unified manner. In order not to affect the efficiency of the report, it is best to use a multi-threaded method to manage tasks. Next, we will introduce the python writing methods of several commonly used methods.

1. Run multiple .py files in multiple threads in python

import os
import threading

reports = ['report1','report2','report3']
filepath = os.getcwd() + '\\' # 或直接写成filepath ="E:\\"

# 定义运行python文件函数
def run_py(i):
    os.system(r'python '+filepath+reports[i]+'.py') # 利用os.system运行文件,后面的r为将引号中的内容当成raw string不解析,此处不写没影响

# 多线程运行python文件
if __name__ == '__main__':
    for i in range(len(reports)):
        task = threading.Thread(target=run_py, args=(i,)) # 注意只有一个参数时后面要加上一个逗号
        task.start()
        # 这种写法不要加上join(),否则反而会变成单线程运行

2. Run multiple .bat files with multiple threads in python, and use bat files to run python

The advantage of using bat to run python is that you can directly double-click to run python in the shell, which is relatively convenient and can be used according to your actual situation

  • Steps to build bat
  • 1. Right-click to create a new txt document
  • 2. Input in the document: python E:\report1.py
  • 3. Save as – file name: report1.bat file type: all files
  • 4. Save
import os
import threading

reports = ['report1','report2','report3']
filepath = os.getcwd() + '\\'

# 定义运行python文件函数
def run_bat(i):
    os.system(filepath+reports[i]+'.bat')

# 多线程运行python文件
if __name__ == '__main__':
    for i in range(len(reports)):
        task = threading.Thread(target=run_bat, args=(i,))
        task.start()
        # 这种写法不要加上join(),否则反而会变成单线程运行

Tips

  • You can write multiple different reports=xxx and comment them out. Use "Ctrl+" to quickly comment which one you want to use when using it
  • If it is a periodic report, you can write a dict to store different file names, and automatically select which files to run according to the current week or date

operation result
insert image description here

Guess you like

Origin blog.csdn.net/lzykevin/article/details/103414167