简体   繁体   English

停止子流程多次启动流程

[英]stop subprocess from initiating a process more than once

I have a pythonic question: lets say I am using the subprocess library in python to run a program from the terminal. 我有一个Python问题:可以说我在python中使用子进程库从终端运行程序。 I need to call the subprocess in a loop. 我需要在循环中调用子流程。 How can I: 1) I stop subprocess from initiating the program if it has already started. 我该怎么办:1)如果程序已经启动,我将阻止其启动子程序。 Or... 2) How can I find out if the program is still running so that I don't initiate a new subprocess? 或者... 2)如何确定程序是否仍在运行,以便不启动新的子进程?

You can check if the process is running using Process.poll . 您可以使用Process.poll检查进程是否正在运行。 It will return None if the process is currently running. 如果该进程当前正在运行,它将返回None Otherwise, it will return the exit code of the sub-process. 否则,它将返回子流程的退出代码。 For example: 例如:

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.

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

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