Python nonblocking console input

2019-01-01 13:32发布

I am trying to make a simple IRC client in Python (as kind of a project while I learn the language).

I have a loop that I use to receive and parse what the IRC server sends me, but if I use raw_input to input stuff, it stops the loop dead in its tracks until I input something (obviously).

How can I input something without the loop stopping?

Thanks in advance.

(I don't think I need to post the code, I just want to input something without the while 1 loop stopping.)

EDIT: I'm on Windows.

7条回答
皆成旧梦
2楼-- · 2019-01-01 14:04

Here a solution that runs under linux and windows using a seperate thread:

import sys
import threading
import time
import Queue

def add_input(input_queue):
    while True:
        input_queue.put(sys.stdin.read(1))

def foobar():
    input_queue = Queue.Queue()

    input_thread = threading.Thread(target=add_input, args=(input_queue,))
    input_thread.daemon = True
    input_thread.start()

    last_update = time.time()
    while True:

        if time.time()-last_update>0.5:
            sys.stdout.write(".")
            last_update = time.time()

        if not input_queue.empty():
            print "\ninput:", input_queue.get()

foobar()
查看更多
登录 后发表回答