问题描述
我正在使用 tkinter
构建一个终端 shell 程序.用户能够运行任意程序(并不总是 python 脚本).这是我开始新流程的方式:
I am building a terminal shell program using tkinter
. The user is able to run any arbitrary program (not always python scripts). This is how I start the new process:
self.proc = subprocess.Popen("test.py", close_fds=False, shell=True, **get_std_child())
这是我的 test.py
程序:
import time
try:
print("Start")
time.sleep(10)
print("End")
except KeyboardInterrupt as error:
print(repr(error), "!")
我在向进程发送 Ctrl-c
事件时遇到问题.我正在使用 Python 3.7.9.我尝试了所有这些,但都没有达到预期的效果.
I am having trouble sending a Ctrl-c
event to the process. I am using 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
根据信号
文档 SIGINT
和 CTRL_C_EVENT
应该在 Windows 上工作.
According to the signal
documentation SIGINT
as well as CTRL_C_EVENT
should work on Windows.
想要的效果和我按Ctrl-c
时cmd的效果一样:
The desired effect is the same as what happens to cmd when I press Ctrl-c
:
C:\Users\TheLizzard\Documents\GitHub\Bismuth-184\src>python test.py
Start
KeyboardInterrupt() !
C:\Users\TheLizzard\Documents\GitHub\Bismuth-184\src>
PS:完整代码在这里但是很长.
PS: The full code is here but it's very long.
推荐答案
如果您想使用 Ctrl + C 杀死 test.py,请尝试类似的操作
If you want to kill test.py using Ctrl + C, then try something like
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.
这篇关于将 Ctrl-C 发送到子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!