如何在python交互式控制台中捕获“Ctrl-D”? [英] How can I capture 'Ctrl-D' in python interactive console?

查看:1735
本文介绍了如何在python交互式控制台中捕获“Ctrl-D”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器在后台运行在一个线程,我使用python -i启动它,所以我可以得到一个交互式控制台,我可以输入命令,轻松调试它。但是当我按Ctrl-D,由于服务器仍然在后台线程中运行,控制台不会退出。如何捕获Ctrl-D事件,以便我可以关闭服务器并正常退出?我知道如何捕获Ctrl-C的信号,但由于我的habbit按Ctrl-D我通常得到一个'卡住'终端,这是真的很讨厌。



谢谢



服务器代码(简化)如下:

 导入线程
import atexit

类WorkerThread(threading.Thread):
def __init __(self):
super(WorkerThread,self).__ init __ $ b self.quit = False

def run(self):
while not self.quit:
pass

def stop(self):
self.quit = True

def q():
printGoodbye!
t.stop()

atexit.register(q)

t = WorkerThread()
t.start()



我使用python -i test.py运行它来获取一个python控制台。

解决方案

使用raw_input(在Python 3.x中使用输入)。按Ctrl + D将导致EOFError异常。

  try:
raw_input()
EOFError:
pass

UPDATE



使用 atexit - 退出处理程序

  import atexit 

def quit_gracefully():
print'Bye'

atexit.register(quit_gracefully )


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. But when I hit Ctrl-D, since the server is still running in a background thread, the console will not quit. How can I capture the Ctrl-D event so that I can shut down the server and quit gracefully? 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.

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.

解决方案

Use raw_input (Use input in Python 3.x). Pressing Ctrl+D will cause EOFError exception.

try:
    raw_input()
except EOFError:
    pass

UPDATE

Use atexit - Exit handlers:

import atexit

def quit_gracefully():
    print 'Bye'

atexit.register(quit_gracefully)

这篇关于如何在python交互式控制台中捕获“Ctrl-D”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆