【发布时间】:2018-08-12 15:18:58
【问题描述】:
我写了这段代码来澄清我的问题...我不断收到 ValueError: I/O operation on closed file。
没有从标准输入读取的子线程。在我启动子线程之前,循环运行良好......有人可以告诉我如何防止文件描述符关闭吗?
import threading
from threadtest2 import Threadtest
import termios, sys, tty
import time
def getchar():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
tt2 = Threadtest()
stop = threading.Event()
t1 = threading.Thread(target=tt2.thread1, args=[stop, ])
t2 = threading.Thread(target=tt2.thread2, args=[stop, ])
try:
while 1:
while not stop.isSet():
try:
c = getchar()
except IOError: pass
if c == "q":
stop.set()
if c == "x":
stop.set()
exit()
if c == "1":
print "starting t1"
t1.start()
if c == "2":
print "starting t2"
t2.start()
while len(threading.enumerate()) > 1:
print 'waiting for ' + str(len(threading.enumerate()) - 1) + ' threads to close\r'
time.sleep(1)
stop.clear()
print "stop has been triggered and reset... restart"
finally:
print "done!"
还有一些其他线程(请原谅双关语)涉及到这一点,但我还没有找到一个直接解决这个问题的线程,并且已经有一段时间了。
仅供参考,子线程只是等待设置停止并休眠......
【问题讨论】:
标签: python multithreading stdin