简体   繁体   中英

Is it possible to interrupt Popen subprocess in python?

from subprocess import Popen, PIPE
command = "ping google.com -t"
with Popen(["cmd", "/c", command], stdout=PIPE, bufsize=1,
           universal_newlines=True) as p:
    for line in p.stdout:
        print(line.strip())

I am using Popen to run a command line argument and capture the output. I would like to send a keystroke to stop this depending on input from the user, but I am not sure how to interrupt the subprocess. In the above example, "Ctrl C" would be required, but in my code I just need to send the letter "q".

Is it possible to do this?

import keyboard  # using module keyboard
from subprocess import Popen, PIPE


command = "ping google.com -t"


while True:  # making a loop
    try:

        with Popen(["cmd", "/c", command], stdout=PIPE, bufsize=1,
               universal_newlines=True) as p:
            for line in p.stdout:
                print(line.strip())

          # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('EXIT  !')
            p.kill()
            break  # finishing the loop
    except:
        break

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