On Fri, Sep 11, 2015 at 11:50 PM, Grant Edwards wrote:
On 2015-09-11, Chris Angelico wrote:

This is what I meant when I said you would be polling. Effectively,
you wake up your program every half-second, check if Ctrl-C has been
pressed, and if it hasn't, you go back to sleep again. This is pretty
Though it offends one's engineering sensibilities[1], it's just not
that inefficient. I'd bet money you won't even be able to measure the
difference in CPU usage. Waking up twice per second and immediately
calling select() again on any hardware/OS built in the past 50 years
is going completely negligible (as long as you can ignore the smell).

Even waking up ten times per second won't be noticeable.

True (although, as Marko says, it can add up). The other difference,
though, is that I like to keep "cope-with-stupidity" code to itself -
ideally, the clean path shouldn't be infected with it. Waking up
periodically with select(), when you otherwise just want a blocking
accept(), affects all your code. Spinning off a thread that monitors
stdin and signals the main thread when it's time to shut down can be
kept to a single block of code, guarded by some sort of platform

import socket

PORT = 8880
mainsock = socket.socket()
mainsock.bind(("", PORT))

if Windows: # however you want to go about checking this
     import threading

     # Python 2/3 compat
     try: input = raw_input
     except NameError: pass

     def console():
         """Constantly read from stdin and discard"""
             while "moar console": input()
         except (KeyboardInterrupt, EOFError):


while "moar sockets":
     s = mainsock.accept()
     print("New connection: %r" % s)
     # Do whatever you want with the connection

As well as keeping the Unix variant stupidity-free, this allows you to
vary your platform check in the event that a future version of Windows
allows blocking calls to be interrupted. Or if a future version of
Python implements this kind of check globally. Or if a Python built
with Cygwin doesn't exhibit this behaviour. Or if PyPy... you get the
idea. The clean path is clearly delineated, and hopefully, the
complexity of your code will increase linearly with the number of
problems you're coping with, rather than having each patch affect each


Search Discussions

Discussion Posts


Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 9 of 11 | next ›
Discussion Overview
grouppython-list @
postedSep 10, '15 at 6:24p
activeSep 11, '15 at 11:15p



site design / logo © 2018 Grokbase