简体   繁体   中英

Python & Subprocess - Monitor process without locking up

I have the idea of creating a control panel to monitor multiple scripts and processes. Having built the interface in advance, I seem to struggle with detecting the status of subprocess commands, getting a locked-up control panel as the child process has started.

There are methods such as subprocess.communicate() or subprocess.wait() to determine whether a process is alive/finished or not, yet those lock up the control panel for the lifetime of the child process. As seen in this block. the if clausule is never reached.

htop = subprocess.Popen(["xterm", "-e", "htop"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = htop.communicate():
if output:
    print("Succeeded!")
else:
    print("status unknown")

How would I be able to control and monitor the new process without locking up the control panel?

The idea is that the panel would be able to start/stop servers, and report on their status:

HTTP server status: running
DHCP server status: stopped

[1] start HTTP server 
[2] start DHCP server
[0] stop all servers

At the moment, it is possible to start a subprocess and see if it did by pressing [1]. It is not however possible to terminate the same subprocess with a different if-statement [0].

使用p.poll()或者,如果你需要检查输出,使用subprocess.PIPE标准输出和select()p.stdout

I've found out how to control the subprocess via two if statements by making the process variable a global variable.

As a result, the code would be as follows (rough sketch):

if command == "run":
    global htop
    htop = subprocess.Popen(["xterm", "-e", "htop"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    if htop.poll() == None:
        htopStatus = "Running"
if command == "stop":
    if htop.poll() == None:
        htop.terminate()
        htopStatus = "Stopped"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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