python调度的独立线程
我正在尝试创建一个守护进程,它运行shell命令,获取结果,并在结束后再次运行它们。将同时运行多个shell命令,因此每个命令必须相互独立。我决定使用Python线程。我写的代码可能有用,但在我看来,它真的是不公平的,你知道如何以更好、更优雅的方式实现它吗 顺便说一句:在这个例子中,我运行两个命令,我想同时运行多个命令python调度的独立线程,python,multithreading,Python,Multithreading,我正在尝试创建一个守护进程,它运行shell命令,获取结果,并在结束后再次运行它们。将同时运行多个shell命令,因此每个命令必须相互独立。我决定使用Python线程。我写的代码可能有用,但在我看来,它真的是不公平的,你知道如何以更好、更优雅的方式实现它吗 顺便说一句:在这个例子中,我运行两个命令,我想同时运行多个命令 import time from daemon import runner import threading class Daemonity(): def __init_
import time
from daemon import runner
import threading
class Daemonity():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/daemonity.pid'
self.pidfile_timeout = 5
def my_function(count, host):
# this is an example function that will execute a ping command on the shell
cmd_run = subprocess.Popen(["ping", "-c", count, host],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
def run(self):
t1 = threading.Thread(name="ping", target=my_function, args=("5", "8.8.8.8"))
t1.daemon = True
t1.start()
t2 = threading.Thread(name="ping2", target=my_function, rgs=("5", "8.8.4.4") )
t2.daemon = True
t2.start()
while True:
time.sleep(2)
if not t1.isAlive():
print "start thread t1"
t1 = threading.Thread(name="ping", target=my_function, rgs=("5", "8.8.8.8"))
t1.daemon = True
t1.start()
if not t2.isAlive():
print "start thread t2"
t2 = threading.Thread(name="ping2", target=my_function, rgs=("5", "8.8.4.4") )
t2.daemon = True
t2.start()
app = Daemonity()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
此代码使进程处于僵死状态,如果计数足够大,足以填充标准输出管道,则将挂起。在线程中使用Popen.communicate,并在线程中使用while循环。我有一个例子,我的函数()只是一个例子,我只对如何使用线程感兴趣除了如何监视和重新启动线程之外,代码没有什么特别不雅的地方。这种事情可以通过队列和工作线程来完成。主线程可以在队列上等待,而不是休眠和轮询。