在一个基本的Unix-shell应用程序中,如何在不干扰任何未决用户输入的情况下打印到stdout。
例如,下面是一个响应用户输入的简单Python应用程序。在后台运行的线程每隔1秒打印一个计数器。
import threading, time
class MyThread( threading.Thread ):
running = False
def run(self):
self.running = True
i = 0
while self.running:
i += 1
time.sleep(1)
print i
t = MyThread()
t.daemon = True
t.start()
try:
while 1:
inp = raw_input('command> ')
print inp
finally:
t.running = False注意线程如何在用户输入时破坏显示的用户输入(例如hell1o wo2rld3)。您将如何解决这一问题,以便shell在保留用户当前键入的行的同时写入新行?
发布于 2010-03-14 07:44:18
您必须将您的代码移植到某种比电传打字稍好的方式来控制终端--例如,使用Python标准库中的curses模块,或者通过其他方式在输出之前将光标移开,然后将其移回用户忙于输入内容的位置。
发布于 2010-03-14 15:38:22
你可以推迟写输出,直到你收到一些输入。对于任何更高级的问题,你必须使用Alex的答案
import threading, time
output=[]
class MyThread( threading.Thread ):
running = False
def run(self):
self.running = True
i = 0
while self.running:
i += 1
time.sleep(1)
output.append(str(i))
t = MyThread()
t.daemon = True
t.start()
try:
while 1:
inp = raw_input('command> ')
while output:
print output.pop(0)
finally:
t.running = Falsehttps://stackoverflow.com/questions/2440387
复制相似问题