Skip to content Skip to sidebar Skip to footer

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. But w

Solution 1:

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)

Solution 2:

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

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.


Post a Comment for "How Can I Capture 'Ctrl-D' In Python Interactive Console?"