停止子进程不止一次启动进程

时间:2014-06-03 02:34:03

标签: python subprocess

我有一个pythonic问题: 假设我在python中使用子进程库从终端运行程序。我需要在循环中调用子进程。 我怎么能够: 1)如果程序已经启动,我会停止启动程序的子进程。要么... 2)如何判断程序是否仍在运行,以便我不启动新的子流程?

1 个答案:

答案 0 :(得分:0)

您可以使用Process.poll检查进程是否正在运行。如果进程当前正在运行,它将返回None。否则,它将返回子进程的退出代码。例如:

import subprocess
import time

p = None
while True:
   if p and p.poll() is None:
       print("Process is currently running. Do nothing.")
   else:  # No process running
       if p:  # We've run the process at least once already, so get the result.
           ret = p.returncode
           print("Last run returned {}".format(ret))
       p = subprocess.Popen(["some_command", "some arg"])
   time.sleep(3)  # Wait a few seconds before iterating again.