2010-03-13 25 views
1

在基本的Unix shell應用程序中,如何打印標準輸出而不干擾任何未決的用戶輸入。在命令行應用程序中打印標準輸出而不覆蓋等待的用戶輸入

例如下面是一個迴應用戶輸入的簡單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在寫入新行時保留用戶當前正在輸入的行?

回答

2

您必須將您的代碼移植到的某些控制終端的方式略好於電傳 - 例如,在Python標準庫中使用curses模塊,或者在發出輸出之前將光標移開的其他方式,然後將其移回用戶忙於輸入內容的位置。

0

您可以延遲寫入輸出,直到您收到一些輸入。對於任何更高級的事情,你必須使用亞歷克斯的答案

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 = False 
相關問題