[英]How to run multiple infinitely looping Python scripts simultaneously
I have a python project which consist of 3 Python scripts that have run indefinitely, and I would like to run them simultaneously. 我有一个python项目,包含3个无限运行的Python脚本,我想同时运行它们。 They are: 他们是:
I tried to run those three files with sh in a shell script. 我尝试在shell脚本中使用sh运行这三个文件。 But once the web.py runs, it seems like the other Python files are waiting in a queue untill web.py finish the job and then are going to be executed. 但是一旦web.py运行,似乎其他Python文件在队列中等待,直到web.py完成作业然后将被执行。 But the web.py will never finish the job, because it keeps looping. 但是web.py永远不会完成这项工作,因为它会不断循环。 I would like the scripts to be executed in this order: web.py, pir.py and then keypadd.py. 我希望脚本按以下顺序执行:web.py,pir.py,然后是keypadd.py。
How can I do that? 我怎样才能做到这一点?
Shell script I used: 我使用的Shell脚本:
#!/bin/sh
# launcher.sh
cd /home/pi/Ptoject
sudo python web.py
sudo python pir.py
sudo python keypadd.py
Another options would be to use a Python wrapper script instead of a shell script, import the functions you need, and run them in other processes: 另一个选择是使用Python包装器脚本而不是shell脚本,导入所需的功能,并在其他进程中运行它们:
import time
import mutliprocessing
import web
import pir
import keypadd
processes = []
for func in [web.function, pir.function, keypadd.function]:
processes.append(multiprocessing.Process(target=func, args=(arg1, arg2)))
processes[-1].start()
# Do stuff
while True:
time.sleep(600) # sleep for 10 minutes
living_processes = [p.is_alive() for p in processes]
if living_processes < 3:
for p in living_processes:
p.terminate()
print("Oops: Some processes died")
# do other error handling here if necessary
There are some nice things about this approach: 这种方法有一些好处:
#!/bin/sh
# launcher.sh
cd /home/pi/Ptoject
sudo python web.py & sudo python pir.py & sudo python keypadd.py
Another solution is use supervisord and daemonize your files. 另一个解决方案是使用supervisord并守护你的文件。
Add an ampersand to fork the process- 添加&符号来分叉流程 -
cd /home/pi/Ptoject
sudo python web.py &
sudo python pir.py &
sudo python keypadd.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.