简体   繁体   中英

Python 3 Stopping subprocess by sending Ctrl C

I have some GPU test software i'm trying to automate using python3, The test would normally be run for 3 minutes then cancelled by a user using ctrl+c generating the following output

GPU测试输出

After exiting with ctrl+c the test can then be run again with no issue

When trying to automate this with subprocess popen and sending SIGINT or SIGTERM i'm not getting the same as if keyboard entry was used. The script exits abruptly and on subsequent runs cant find the gpus (assume its not unloading the driver properly)

from subprocess import Popen, PIPE
from signal import SIGINT
from time import time


def check_subproc_alive(subproc):
    return subproc.poll() is None

def print_subproc(subproc, timer=True):
    start_time = time()
    while check_subproc_alive(subproc):
        line = subproc.stdout.readline().decode('utf-8')
        print(line, end="")
        if timer and (time() - start_time) > 10:
            break


subproc = Popen(['./gpu_test.sh', '-t', '1'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)

print_subproc(subproc)

subproc.send_signal(SIGINT)

print_subproc(subproc, False)

How can I send ctrl+c to a subprocess as if a user typed it?

**UPDATE

import subprocess


def start(executable_file):
    return subprocess.Popen(
        executable_file,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )


def read(process):
    return process.stdout.readline().decode("utf-8").strip()


def write(process):
    process.stdin.write('\x03'.encode())
    process.stdin.flush()

def terminate(process):
    process.stdin.close()
    process.terminate()
    process.wait(timeout=0.2)


process = start("./test.sh")
write(process)
for x in range(100):
    print(read(process))
terminate(process)

Tried the above code and can get characters to register with dummy sh script however sending the \\x03 command just sends an empty char and doesn't end script

I think you can probably use something like this:

import signal
try:
    p=subprocess...
except KeyboardInterrupt:
    p.send_signal(signal.SIGINT)

The following solution is the only one I could find that works for windows and is the closest resemblance to sending a Ctrl+C event.

import signal
os.kill(self.p.pid, signal.CTRL_C_EVENT)

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