我正在使用tkinter
构建一个终端外壳程序。用户能够运行任意程序(并不总是python脚本)。下面是我开始新流程的方式:
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。我尝试了所有这些方法,但都没有达到预期的效果。
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
根据signal
documentation的说法,SIGINT
和CTRL_C_EVENT
应该可以在Windows上运行。
所需的效果与按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:完整的代码是here,但它很长。
发布于 2021-03-27 22:55:30
如果您想要使用Ctrl + C杀死test.py,那么尝试如下所示
def signal_handler(signal):
self.proc.terminate()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
如果有任何问题,请随时发表意见。
https://stackoverflow.com/questions/66829864
复制相似问题