简体   繁体   English

将 Ctrl-C 发送到子进程

[英]Sending Ctrl-C to a child process

I am building a terminal shell program using tkinter .我正在使用tkinter构建终端 shell 程序。 The user is able to run any arbitrary program (not always python scripts).用户能够运行任意程序(并非总是 python 脚本)。 This is how I start the new process:这就是我开始新流程的方式:

self.proc = subprocess.Popen("test.py", close_fds=False, shell=True, **get_std_child())

This is my test.py program:这是我的test.py程序:

import time
try:
    print("Start")
    time.sleep(10)
    print("End")
except KeyboardInterrupt as error:
    print(repr(error), "!")

I am having trouble sending a Ctrl-c event to the process.我在向进程发送Ctrl-c事件时遇到问题。 I am using Python 3.7.9.我正在使用 Python 3.7.9。 I tried all of these but none of them have the desired effect.我尝试了所有这些,但都没有达到预期的效果。

from signal import SIGINT, CTRL_C_EVENT, CTRL_BREAK_EVENT
proc.send_signal(SIGINT) # `ValueError: Unsupported signal: 2`
os.kill(proc.pid, SIGINT) # Doesn't do anything until I press it again then it throws: PermissionError: [WinError 5] Access is denied
os.kill(proc.pid, CTRL_C_EVENT) # SystemError: <built-in function kill> returned a result with an error set
os.kill(proc.pid, CTRL_BREAK_EVENT) # SystemError: <built-in function kill> returned a result with an error set

According to the signal documentation SIGINT as well as CTRL_C_EVENT should work on Windows.根据signal文档SIGINTCTRL_C_EVENT应该在 Windows 上工作。

The desired effect is the same as what happens to cmd when I press Ctrl-c :所需的效果与我按下Ctrl-c时 cmd 发生的情况相同:

C:\Users\TheLizzard\Documents\GitHub\Bismuth-184\src>python test.py
Start
KeyboardInterrupt() !

C:\Users\TheLizzard\Documents\GitHub\Bismuth-184\src>

PS: The full code is here but it's very long. PS:完整的代码在这里但是很长。

If you want to kill test.py using Ctrl + C, then try something like如果您想使用 Ctrl + C 杀死 test.py,请尝试类似

def signal_handler(signal):
            self.proc.terminate()
            sys.exit(0)
        
signal.signal(signal.SIGINT, signal_handler)

Feel free to comment in case of any question.如有任何问题,请随时发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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