[英]How can I capture 'Ctrl-D' in python interactive console?
I have a server which runs in a thread in the background, and I start it using python -i so I can get an interactive console where I can type in commands and easily debug it. 我有一个服务器在后台的一个线程中运行,我使用python -i启动它,所以我可以得到一个交互式控制台,我可以输入命令并轻松调试它。 But when I hit Ctrl-D, since the server is still running in a background thread, the console will not quit.
但是当我按下Ctrl-D时,由于服务器仍在后台线程中运行,因此控制台不会退出。 How can I capture the Ctrl-D event so that I can shut down the server and quit gracefully?
如何捕获Ctrl-D事件以便我可以关闭服务器并正常退出? I know how to capture Ctrl-C with signals, but due to my habbit of pressing Ctrl-D I usually get a 'stuck' terminal which is really annoying.
我知道如何用信号捕获Ctrl-C,但是由于我按下Ctrl-D的习惯,我通常得到一个“卡住”的终端,这真的很烦人。
Thanks! 谢谢!
The server code (simplified) is like this: 服务器代码(简化)是这样的:
import threading
import atexit
class WorkerThread(threading.Thread):
def __init__(self):
super(WorkerThread, self).__init__()
self.quit = False
def run(self):
while not self.quit:
pass
def stop(self):
self.quit = True
def q():
print "Goodbye!"
t.stop()
atexit.register(q)
t = WorkerThread()
t.start()
and I run it using python -i test.py to get a python console. 然后我使用python -i test.py运行它以获得一个python控制台。
Use raw_input (Use input in Python 3.x). 使用raw_input(在Python 3.x中使用输入)。 Pressing Ctrl+D will cause EOFError exception.
按Ctrl + D将导致EOFError异常。
try:
raw_input()
except EOFError:
pass
UPDATE UPDATE
Use atexit - Exit handlers : 使用atexit - 退出处理程序 :
import atexit
def quit_gracefully():
print 'Bye'
atexit.register(quit_gracefully)
I have exactly the same problem like you and I've fixed it. 我有像你一样的问题,我已经修好了。 I've found a good answer in a comment located here : http://www.regexprn.com/2010/05/killing-multithreaded-python-programs.html?showComment=1336485652446#c8921788477121158557
我在这里的评论中找到了一个很好的答案: http : //www.regexprn.com/2010/05/killing-multithreaded-python-programs.html?showComment = 1336485652446 #c8921788477121158557
Here, the comment : 在这里,评论:
"You can always set your threads to "daemon" threads like: “你总是可以将你的线程设置为”守护进程“线程,如:
t.daemon = True
t.start()
And whenever the main thread dies all threads will die with him ^^" 每当主线程死亡时,所有线程都将与他一起死亡^^“
Thank's to OP for his question and thank's to comment author for his sharing. 感谢OP提出的问题,感谢评论作者的分享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.