3
while True:
  mess = raw_input('Type: ')
  //other stuff

虽然用户没有输入任何内容,但我做不到//other stuff. 我该怎么办,其他东西会被执行,但是,如果用户当时输入任何东西,混乱会改变它的价值?

4

2 回答 2

4

您应该在工作线程中生成其他内容。

import threading
import time
import sys

mess = 'foo'

def other_stuff():
  while True:
    sys.stdout.write('mess == {}\n'.format(mess))
    time.sleep(1)

t = threading.Thread(target=other_stuff)
t.daemon=True
t.start()

while True:
  mess = raw_input('Type: ')

这是一个mess作为全局的简单示例。请注意,对于工作线程和主线程之间的对象的线程安全传递,您应该使用Queue对象在线程之间传递事物,不要使用全局对象。

于 2012-02-27T02:01:48.367 回答
0

作为使用工作线程的替代方法,您可以通过以下方式轮询用户输入在 Unix 上是否可用select.select()

import select
import sys

def raw_input_timeout(prompt=None, timeout=None):
    if prompt is not None:
        sys.stdout.write(prompt)
        sys.stdout.flush()
    ready = select.select([sys.stdin], [],[], timeout)[0]
    if ready:
        # there is something to read
        return sys.stdin.readline().rstrip('\n')

prompt = "First value: "
while True:
    s = raw_input_timeout(prompt, timeout=0)
    if s is not None:
        mess = s # change value
        print(repr(mess))
        prompt = "Type: " # show another prompt
    else:
        prompt = None # hide prompt
    # do other stuff

每次用户按下Entermess值都会改变。

于 2012-02-27T02:56:58.997 回答