Background thread

Jp Calderone exarkun at divmod.com
Sat Jun 25 06:50:07 EDT 2005


On Sat, 25 Jun 2005 11:36:57 +0100, Jorge Louis De Castro <jorge at bcs.org.uk> wrote:
>Hi,
>
>I'm new to python and I'm having trouble figuring out a way to have a thread running on the background that over rules the raw_input function. The example I'm working on is something like having a thread that prints "You're taking too long" every 10 seconds, while waiting for input from the user.
>The problem is that I can only read (and in batch) the thread printout messages on the console after giving something to raw_input.
>Is it not possible to have the thread print its stuff and then return to raw_input() ? Any code examples or pseudo-code or documentation directions will be highly appreciated.
>
>Thanks in advance
>

Here's one way you might do it without threads or raw_input()

  from twisted.protocols import basic, policies

  class AnnoyProtocol(basic.LineReceiver, policies.TimeoutMixin):
      from os import linesep as delimiter

      def connectionMade(self):
          self.setTimeout(10)

      def timeoutConnection(self):
          self.resetTimeout()
          self.sendLine("You're taking too long!")

      def lineReceived(self, line):
          self.resetTimeout()
          self.sendLine("Thank you for the line of input!")

  from twisted.internet import reactor, stdio
  stdio.StandardIO(AnnoyProtocol())
  reactor.run()

For fancy line editing support, twisted.conch.recvline might be of interest.

Hope this helps,

Jp



More information about the Python-list mailing list