python用户输入的是q吗_如何在python线程中读取用户输入?

1586010002-jmsa.png

I'm trying to read from a thread in python as follows

import threading, time, random

var = True

class MyThread(threading.Thread):

def set_name(self, name):

self.name = name

def run(self):

global var

while var == True:

print "In mythread " + self.name

time.sleep(random.randint(2,5))

class MyReader(threading.Thread):

def run(self):

global var

while var == True:

input = raw_input("Quit?")

if input == "q":

var = False

t1 = MyThread()

t1.set_name("One")

t2 = MyReader()

t1.start()

t2.start()

However, if I enter 'q', I see the following error.

In mythread One

Quit?q

Exception in thread Thread-2:

Traceback (most recent call last):

File "/usr/lib/python2.6/threading.py", line 522, in __bootstrap_inner

self.run()

File "test.py", line 20, in run

input = raw_input("Quit?")

EOFError

In mythread One

In mythread One

How does on get user input from a thread?

解决方案

Your code is a bit strange. If you are using the reader strictly to quit the program, why not have it outside the threading code entirely? It doesn't need to be in the thread, for your purposes, and won't work in the thread.

Regardless, I don't think you want to take this road. Consider this problem: multiple threads stop to ask for input simultaneously, and the user types input. To which thread should it go? I would advise restructuring the code to avoid this need.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值