每y秒运行python子进程x秒

时间:2011-08-07 03:36:44

标签: python subprocess sleep wait

我想从Python中控制一个bash程序。我想每隔x秒运行一次外部命令,持续y秒,然后在y秒之后将其杀死。我在线程,睡眠和等待等方面遇到了一些麻烦,我想知道是否有人可以发布一个简单的例子。

例如,从CLI可以使用

./foo.py --runfor=10 --runevery=60

意味着foo.py每60秒运行一次10秒(而不是60秒)。如果它关闭一秒钟或几分之一秒即可。我可以通过生成一个阻塞的进程,然后做一些数学来设置计时器来做到这一点,但我认为线程可能有更优雅的方式。

2 个答案:

答案 0 :(得分:6)

这有帮助吗?

import threading
import subprocess
import time

class IntervalRunner(threading.Thread):
    def __init__(self, seconds):
        self.seconds = seconds
        threading.Thread.__init__(self)

    def run(self):
        while True:
            p = subprocess.Popen('ls -la'.split(), shell=False,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)

            stdout, stderr = p.communicate()
            print stdout
            time.sleep(self.seconds)

runner = IntervalRunner(10)
runner.start()
runner.join()

答案 1 :(得分:0)

您可以尝试python的apscheduler模块。它类似于cron风格的调度。 http://packages.python.org/APScheduler/

相关问题