简体   繁体   English

每y秒运行python子进程x秒

[英]Run python subprocess for x seconds every y seconds

I'd like to control a bash program from within Python. 我想从Python中控制bash程序。 I'd like to run an external command every x seconds for y seconds, and then kill it after y seconds. 我想在y秒内每隔x秒运行一个外部命令,然后在y秒后杀死它。 I'm having a bit of trouble with threads and sleep and wait and etc. and am wondering if someone can post a simple example. 我在线程,睡眠和等待等方面遇到了一些麻烦,并且想知道是否有人可以发布一个简单的示例。

For example, from the CLI the usage might be 例如,在CLI中,用法可能是

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

meaning foo.py would run something for 10 seconds every 60 seconds (not 60 seconds between). 意味着foo.py每60秒(而不是60秒之间)运行10秒。 If it is off by a second or fractions of a second that is OK. 如果关闭一秒或几分之一秒就可以了。 I can do this by spawning a process that is blocking, and then doing some math to set the timer, but I think there might be a more elegant way with threads. 我可以通过产生一个正在阻塞的进程,然后进行一些数学运算来设置计时器来做到这一点,但我认为使用线程可能会有更优雅的方式。

does this help? 这有帮助吗?

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

You can try the apscheduler module of python.It is similar to a cron-style scheduling. 您可以尝试使用python的apscheduler模块,类似于cron样式的调度。 http://packages.python.org/APScheduler/ http://packages.python.org/APScheduler/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM