2013-01-23 17 views
0

基本上這個代碼從管道讀取並不斷打印輸出而不會阻塞...這裏是整個代碼:呼叫腳本而不阻斷解釋需要

1)第一腳本:

if __name__ == '__main__': 
    for i in range(5): 
     print str(i)+'\n', 
     sys.stdout.flush() 
     time.sleep(1) 

2)第二個腳本:

def log_worker(stdout): 

    while True: 
     output = non_block_read(stdout).strip() 
     if output: 
      print output 


def non_block_read(output): 
    ''' even in a thread, a normal read with block until the buffer is full ''' 
    fd = output.fileno() 
    fl = fcntl.fcntl(fd, fcntl.F_GETFL) 
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) 
    try: 
     return output.read() 
    except: 
     return '' 

if __name__ == '__main__': 

    mysql_process = subprocess.Popen(['python','-u', 'flush.py'], stdin=sys.stdin, 
     stdout=subprocess.PIPE, 
     stderr=subprocess.PIPE) 


    thread = Thread(target=log_worker, args=[mysql_process.stdout]) 
    thread.daemon = True 
    thread.start() 

    mysql_process.wait() 
    thread.join(timeout=1) 

我想知道爲什麼它的工作原理是這樣:

1)如果我把Thread全部拿走,並且在main中調用log_worker也會一一打印所有內容,但問題是它在完成後會掛起而沒有完成。而且我在某處讀到這裏的線程完全用於完成或更正確的線程死亡時,它完成打印的東西,那麼它爲什麼這樣工作?在這裏以及如何做什麼線程?

2)如果我保持線程,但刪除mysql_process.wait()和thread.join它不打印....爲什麼?我讀過Popen.wait是爲了它的子進程終止。設置並返回returncode屬性。這裏的孩子過程是什麼,爲什麼/如何是孩子O_O?

3)如果我只刪除thread.join(timeout = 1),那麼它完成但錯誤Exception in thread Thread-1 (most likely raised during interpreter shutdown):。爲什麼?在這裏扮演什麼角色。

4)我讀了non_block_read函數中使用的函數的文檔,但仍然很困惑。好吧,很明顯,他們採取文件描述符並將其設置爲非阻塞。我感到困惑的是,我可以使用所有這些函數,我的意思是我明白文件上,但他們如何使用它在標準輸出O_O?這不是一個文件,它是一個流~~?

我所做的這一切都是通過subprocess.Popen在龍捲風腳本中執行腳本,並不斷髮送輸出給客戶端/我自己而不會阻塞,所以如果任何人都可以幫助我這麼做,我會非常感激,因爲我可以「難以想象如何樣得到線程這個輸出的方式,我可以constanly插入它在tornadio2 self.send ...

def on_message(self, message): 
#  list = subprocess.Popen([r"ls", "-l"], stdout=subprocess.PIPE) 
#  list_stdout = list.communicate()[0] 
     for i in range(1,10): 
      time.sleep(1) 
      self.send(i) 

回答

0

隨着開發的版本(3.2),這是真的容易

from tornado.web import RequestHandler,asynchronous 
from tornado.process import Subprocess 

class home(RequestHandler): 
    @asynchrounous 
    def get(self): 
    seld.sp=Subprocess('date && sleep 5 && date',shell=True,stdout=Subprocess.STREAM) 
    self.sp.set_exit_callback(self.next) 
    def next(self,s): 
    self.sp.stdout.read_until_close(self.finish) 

application = ...