python预定独立线程

时间:2013-12-04 17:52:27

标签: python multithreading

我正在尝试创建一个运行shell命令的守护进程,获取结果并在结束时重新运行它们。将同时运行多个shell命令,因此每个命令必须独立于另一个。我决定使用Python线程。我写的代码可能有用,但在我看来真的很不优雅,你知道如何以更好,更优雅的方式实现它吗?

BTW:在这个例子中我运行了2个命令,我想同时运行很多命令。

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()

0 个答案:

没有答案