2

我想同时从一个master script. 这些脚本中的每一个都已经在其中包含并行运行的线程。例如我跑

脚本1.py

if __name__ == '__main__':
    pid_vav = PID_VAV('B2')
    t1 = threading.Thread(target=pid_vav.Controls)
    t1.daemon = False
    t1.start()
    t2 = threading.Thread(target=pid_vav.mqttConnection)
    t2.daemon = False
    t2.start()

脚本2.py

if __name__ == '__main__':
    pid_vav = PID_VAV('B4')
    t1 = threading.Thread(target=pid_vav.Controls)
    t1.daemon = False
    t1.start()
    t2 = threading.Thread(target=pid_vav.mqttConnection)
    t2.daemon = False
    t2.start()

我正在单独运行script1.pyscript2.py。唯一的区别是我传递给班级的参数。是否有可能有一个主脚本,如果我只运行它,这两个脚本都会运行?

谢谢

4

4 回答 4

2

如果您想从主脚本触发 2 个脚本,您可以使用以下方法。它将帮助您将两个脚本作为线程触发,并且该线程还可以根据可调用脚本生成不同的线程。您甚至可以使脚本独立运行。

import subprocess

pid1 = subprocess.Popen([sys.executable, "script1.py"]) 
pid2 = subprocess.Popen([sys.executable, "script2.py"]) 
于 2020-01-31T13:37:15.540 回答
2

假设您希望在运行主脚本时显示两个脚本的输出。
可以利用subprocess模块调用python文件,也可以利用threading模块启动单独的线程

from threading import Thread
import subprocess

t1 = Thread(target=subprocess.run, args=(["python", "script1.py"],))
t2 = Thread(target=subprocess.run, args=(["python", "script2.py"],))

t1.start()
t2.start()

t1.join()
t2.join()

于 2020-02-09T19:52:14.127 回答
1

是的,ofc。

script_master.py:

from os import system
system('start script1.py && start script2.py')

但我认为你可以使用这段代码:

script_together.py:

if __name__ == '__main__':
    todo=[]

    todo.append(threading.Thread(target=lambda: PID_VAV('B2').Controls, daemon=False))
    todo.append(threading.Thread(target=lambda: PID_VAV('B4').mqttConnection, daemon=False))
    for th in todo:
        th.start()
    for th in todo:
        th.join()
于 2020-01-31T10:24:38.893 回答
0

如果您很高兴将两者的代码放在一个文件中,则可以使用多处理在不同的 CPU 内核上同时运行它们。

import multiprocessing as mp
from threading import Thread

def start_process(pid_vav_label):
    pid_vav, threads = PID_VAV(pid_vav_label), []
    threads.append(Thread(target=pid_vav.Controls))
    threads.append(Thread(target=pid_vav.mqttConnection))
    for thread in threads:
        thread.start()
    # Join if necessary
    for thread in threads:
        thread.join()

if __name__ == '__main__':
    processes = []
    for label in ['B2', 'B4']:
        processes.append(mp.Process(target=start_process, args=(label,)))
        processes[-1].start()
    # Again, can join if necessary
    for process in processes:
        process.join()
于 2020-02-09T20:37:28.010 回答