我有一个 python 脚本 script01.py 它需要 4 个参数
我在批处理命令中启动 script01.py,如下所示: python script01.py arg1 arg2 arg3 arg4
现在我想使用 Thread (或任何合适的方法)并行启动 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
...
我该如何处理这个问题?
谢谢
听起来您需要一个控制函数,然后线程化并启动 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