12

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.

Chi Zhang
  • 771
  • 2
  • 8
  • 22

2 Answers2

17

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)
falsetru
  • 357,413
  • 63
  • 732
  • 636
3

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"

S.B
  • 13,077
  • 10
  • 22
  • 49
MlleParker
  • 51
  • 3
  • IMO this is the correct answer here, if there's a non-daemon thread running and you press `^D` then `atexit` will not save you. – MoxieBall Jun 04 '18 at 15:42