编程语言
首页 > 编程语言> > python-用户决定是否在raw_input中写东西时如何做其他事情?

python-用户决定是否在raw_input中写东西时如何做其他事情?

作者:互联网

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

虽然用户什么也没输入,但我不能做其他事情.我该怎么办,其他东西会被执行,但是,如果用户当时输入任何东西,乱七八糟会改变它的价值?

解决方法:

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

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: ')

这是一个琐碎的例子,将混乱当成一个整体.请注意,为了在工作线程和主线程之间进行线程安全的对象传递,应使用Queue对象在线程之间传递事物,而不要使用全局对象.

标签:raw-input,multithreading,python
来源: https://codeday.me/bug/20191101/1985159.html