使用龙卷风自己的
process.Subprocess
类,它是stdlib的包装器。
subprocess.Popen
.
例子:
from tornado import process
@gen.coroutine
def longProcess():
bashCommand = "sleep 5 && echo hi"
proc = process.Subprocess(bashCommand.split(), stdout=subprocess.PIPE)
yield proc.wait_for_exit() # `wait_for_exit` returns a future
# which you can yield. Basically, it means
# you can wait for the process to complete
# without blocking the server
return proc.stdout.read() # return the result of the process
# for Python 2:
# you can't return from a generator
# instead use this:
# raise gen.Return(proc.stdout.read())
你不需要
while
循环。您可以将代码移到其他的协同程序中,并生成列表。
futures
. 这样地:
@gen.coroutine
def main():
futures = [longProcess() for x in range(0, 5)]
results = yield futures # this coroutine will not move further
# until every future in the list
# `futures` is resolved
for result in results:
print(result)
print('All futures resolved')
作为补充说明,不要使用
time.sleep
. 它会阻塞整个服务器。而是使用异步等效
gen.sleep
-
yield gen.sleep(1)