我想从 Python 中控制 bash 程序。我想每 x 秒运行一个外部命令,持续 y 秒,然后在 y 秒后杀死它。我在线程、 sleep 和等待等方面遇到了一些麻烦,我想知道是否有人可以发布一个简单的示例。
例如,从 CLI 中,用法可能是
./foo.py --runfor=10 --runevery=60
意味着 foo.py
会每 60 秒运行一次 10 秒(而不是间隔 60 秒)。如果偏离一秒或几分之一秒也没关系。我可以通过生成一个阻塞的进程,然后进行一些数学运算来设置计时器来做到这一点,但我认为可能有一种更优雅的线程方式。
最佳答案
这有帮助吗?
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()
关于python - 每 y 秒运行 python 子进程 x 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970574/