问题描述
Index value
1 a
2 a
3 v
4 v
5 v
6 v
7 v
8 h
我正在使用Popen运行命令行参数并捕获输出。我想发送击键来停止此操作,具体取决于用户的输入,但是我不确定如何中断子进程。在上面的示例中,将需要“ Ctrl C”,但是在我的代码中,我只需要发送字母“ q”。
可以这样做吗?
解决方法
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