Python - 线程调用带参数的脚本

0 投票
1 回答
26 浏览
提问于 2025-04-12 13:19

我有一个叫做script01.py的Python脚本,它需要4个参数。

我通常是通过批处理命令来运行这个脚本,比如这样:python script01.py arg1 arg2 arg3 arg4。

现在我想要同时运行script01.py,也就是并行运行,并且传入这些参数:

Thread 1 launchs : script01.py A B C D
Thread 2 launchs : script01.py E F G H
Thread 3 launchs : script01.py I J K L
...

我该怎么做呢?

谢谢!

1 个回答

0

听起来你需要一个控制函数,然后去执行并启动script01.py这个脚本。

为了举个例子,script01其实就是一个函数。

import threading
import time


def script01(thread_name, numbers): # Square of numbers
    for number in numbers:
        print(thread_name, number**2)
        time.sleep(1)

def launcher(*args):
    size = len(args)
    group = size // 4
    threads = {}
    for i in range(group):
        threads[i] = threading.Thread(target=script01, args=("thread" + str(i), args[i*4:(i+1)*4]))
    for i in range(group):
        threads[i].start()
    for i in range(group): # Joins the threads to wait for all to be complete before moving on. 
        threads[i].join()

if __name__ == "__main__":
    launcher(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)

输出的结果看起来是这样的:

thread0 1
thread1 25
thread2 81
thread3 169
thread0 4
thread2 100
thread3 196
thread1 36
thread0 9
thread3 225
thread2 121
thread1 49
thread0 16
thread1 64
thread2 144
thread3 256

撰写回答