[英]How to kill a Windows subprocess in Python when it expects a key but simply doesn't react to it through stdin?
我正在尝试杀死一个子进程,该子进程期望在终端中按下“q”以便优雅地停止。
这个可执行文件有两种运行模式(两种都试过):
我尝试使用subprocess.Popen(command_parts)
生成子进程,其中command_parts
是一个包含可执行文件的列表,它是各种标志。
我以多种组合将以下 arguments 添加到 Popen 构造函数中:
creationflags=subprocess.DETACHED_PROCESS
stdin=PIPE
我尝试将以下字符串发送到可执行文件的标准输入:
b"q"
b"q\n"
b"q\r\n"
我尝试通过以下方式与可执行文件进行通信:
subprocess_instance.communicate(input_stuff)
subprocess_instance.stdin.write(input_stuff); subprocess_instance.stdin.flush()
这些尝试都不会导致可执行文件优雅地关闭,并且会永远徘徊,就好像标准输入上没有发生任何事情一样。
观察:
更新:
我尝试使用等待“q”的示例 C 程序:
#include <stdio.h>
#include <conio.h>
int main(int argc, char const *argv[]) {
printf("Hello world\n");
printf("Waiting for char ...\n");
while (1) {
unsigned int x = getch();
printf("PRESSED: %c\n", x);
if (x == 'q') {
printf("Quitting ...\r\n");
break;
};
}
printf("\n----\n");
printf("DONE\n\n");
return 0;
}
然后我试图用来运行它的脚本是:
import time
import subprocess as sp
import pathlib as plib
def main() -> None:
print("\nSTARTING")
print("Create subproces ...");
exe_path = plib.Path('guinea_pig_executable/bla.exe').absolute()
exe_path_str = str(exe_path)
exe = sp.Popen(
[exe_path_str],
stdin=sp.PIPE,
stdout=sp.PIPE,
stderr=sp.PIPE,
)
print("Wait ...")
time.sleep(5)
print("Try quitting ...")
try:
exe.communicate(b'q\r\n', timeout=2)
# exe.stdin.write(b'q')
# exe.stdin.flush()
except Exception as err:
print(repr(err))
print("Wait for sub proc to die ...")
try:
exe.wait(timeout=5)
except sp.TimeoutExpired as terr:
print("Timeout error", repr(terr))
exe.kill() # forcefully killing
print("\nEND\n---\n")
if __name__ == '__main__':
main()
我得到的 output 是:
PS E:\workspace\try-kill-exe> python .\main.py
STARTING
Create subproces ...
Wait ...
Try quitting ...
TimeoutExpired(['E:\\workspace\\try-kill-exe\\guinea_pig_executable\\bla.exe'], 2)
Wait for sub proc to die ...
Timeout error TimeoutExpired(['E:\\workspace\\try-kill-exe\\guinea_pig_executable\\bla.exe'], 5)
END
---
这可能是什么原因? 这是 windows 特定的东西吗? 是不是 Python 处理不了的东西? 我还可以尝试哪些其他事情?
当涉及到按键时,python 脚本可以通过多种方式与子进程通信。
user32.dll
(感谢@john-hen -> 灵感来自https://stackoverflow.com/a/8117562/858565 )
Package: https://pypi.org/project/pywin32/
import win32console
def make_keydown_input(c) -> None:
input_record = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
input_record.KeyDown = 1
input_record.RepeatCount = 1
input_record.Char = c
return input_record
console_handler = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
q_keydown = make_keydown_input('q')
console_handler.WriteConsoleInput([q_keydown])
Package: https://pypi.org/project/pynput/
import pynput
keyb_controller = pynput.keyboard.Controller()
keyb_controller.press('q')
Package: https://pypi.org/project/PyAutoGUI/
示例: https://pyautogui.readthedocs.io/en/latest/keyboard.html
这可能是最简单的方法。
import pyautogui
pyautogui.press('q')
user32.dll
请参考这个答案: https://stackoverflow.com/a/13615802/858565
最后你只需要打电话:
PressKey(0x51)
其中0x51
是q
的十六进制键码( https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes )
请注意,所有这些方法都将在调用它的程序的上下文中应用按键。 我还没有尝试过 multiprocessing.Process,也许它会做出不同的反应。
可能要拥有一个良好的隔离上下文,必须在隔离的 python 脚本中运行特定的子进程,该脚本只是通过套接字从外部接收消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.