通过subprocess.Popen调用脚本而不需要阻止解释

时间:2013-01-23 18:59:50

标签: subprocess tornado

基本上这段代码从管道读取并不断打印输出而不会阻塞......以下是整个代码:

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):。为什么? .join扮演什么角色。

4)我阅读了non_block_read函数中使用的函数的文档,但仍然感到困惑。好的很明显,他们采用文件描述符并将其设置为非阻塞。我感到困惑的是,我可以使用所有这些功能,我的意思是我理解文件,但是为什么他们在stdout O_O上使用它?它不是一个文件,它是一个流~~?

所有这些我用龙卷风脚本中的subprocess.Popen执行脚本,并不断阻止向客户端/我自己发送输出,所以如果有人可以帮助我这样做,我会非常感激,因为我可以'想象一下如何以一种我可以在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)

1 个答案:

答案 0 :(得分: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 = ...
相关问题