A non-blocking read on a subprocess.PIPE in Python

后端 未结 29 2593
醉酒成梦
醉酒成梦 2020-11-21 04:49

I\'m using the subprocess module to start a subprocess and connect to its output stream (standard output). I want to be able to execute non-blocking reads on its standard ou

29条回答
  •  日久生厌
    2020-11-21 04:52

    Disclaimer: this works only for tornado

    You can do this by setting the fd to be nonblocking and then use ioloop to register callbacks. I have packaged this in an egg called tornado_subprocess and you can install it via PyPI:

    easy_install tornado_subprocess
    

    now you can do something like this:

    import tornado_subprocess
    import tornado.ioloop
    
        def print_res( status, stdout, stderr ) :
        print status, stdout, stderr
        if status == 0:
            print "OK:"
            print stdout
        else:
            print "ERROR:"
            print stderr
    
    t = tornado_subprocess.Subprocess( print_res, timeout=30, args=[ "cat", "/etc/passwd" ] )
    t.start()
    tornado.ioloop.IOLoop.instance().start()
    

    you can also use it with a RequestHandler

    class MyHandler(tornado.web.RequestHandler):
        def on_done(self, status, stdout, stderr):
            self.write( stdout )
            self.finish()
    
        @tornado.web.asynchronous
        def get(self):
            t = tornado_subprocess.Subprocess( self.on_done, timeout=30, args=[ "cat", "/etc/passwd" ] )
            t.start()
    

提交回复
热议问题