线程休眠导致stdin阻塞
我正在运行一个函数,这个函数用来处理通过标准输入(stdin)传入的命令,还有另一个函数用来执行一系列的任务。我需要让后一个函数定期“休息”,但这样似乎会阻塞标准输入。有没有什么建议可以解决这个问题?
这两个函数的源代码是
def runJobs(comps, jobQueue, numRunning, limit, lock):
while len(jobQueue) >= 0:
print(len(jobQueue));
if len(jobQueue) > 0:
comp, tasks = find_computer(comps, 0);
#do something
time.sleep(5);
def manageStdin():
print "Global Stdin Begins Now"
for line in fileinput.input():
try:
print(eval(line));
except Exception, e:
print e;
--谢谢
1 个回答
1
使用单线程:
import time
import select
import logging
import sys
def stdinWait(interval):
start = time.time()
while True:
time_left = interval - (time.time() - start)
if time_left <= 0:
break
r, w, x = select.select([sys.stdin], [], [], time_left)
if r:
line = r[0].readline()
try:
print(eval(line));
except Exception, e:
logging.exception(e)
def runJobs(comps, jobQueue, numRunning, limit, lock):
while len(jobQueue) >= 0:
print(len(jobQueue));
if len(jobQueue) > 0:
comp, tasks = find_computer(comps, 0);
#do something
stdinWait(5) # wait 5 seconds while watching stdin