2

我正在試驗一下python的asyncio協議。我從官方文檔中發現this example,並希望稍微修改它並重現它的beahviour。所以我寫了下面兩個腳本:Python asyncio簡單示例

# file: get_rand.py 
from random import choice 
from time import sleep 

def main(): 
    print(choice('abcdefghijklmnopqrstuvwxyz')) 
    sleep(2) 

if __name__ == '__main__': 
    main() 

和:

# file: async_test.py 
import asyncio 

class Protocol(asyncio.SubprocessProtocol): 

    def __init__(self, exit_future): 
     self.exit_future = exit_future 
     self.output = bytearray() 
     print('Protocol initialised') 

    def pipe_data_received(self, fd, data): 
     print('Data received') 
     self.output.extend(data) 

    #def pipe_connection_lost(self, fd, exc): 
    # print('Pipe connection lost for the following reason:') 
    # print(exc) 

    def subprocess_exited(self): 
     print('Subprocess exited') 
     self.exit_future.set_result(True) 


@asyncio.coroutine 
def get_rand(loop): 
    exit_future = asyncio.Future(loop=loop) 
    print('Process created') 
    created = loop.subprocess_exec(lambda: Protocol(exit_future), 
            'python3.5', 'get_rand.py', 
            stdin=None, stderr=None) 
    print('Getting pipes...') 
    transport, protocol = yield from created 
    print('Waiting for child to exit...') 
    yield from exit_future 
    transport.close() 
    print('Gathering data...') 
    data = bytes(protocol.output) 
    print('Returning data...') 
    return data.decode('ascii').rstrip() 

def main(): 
    loop = asyncio.get_event_loop() 
    print('Event loop started') 
    data = loop.run_until_complete(get_rand(loop)) 
    print('Event loop ended') 
    print(data) 
    loop.close() 

if __name__ == '__main__': 
    main() 

當我運行async_test.py我得到以下的輸出:

$ python3.5 async_test.py 
Event loop started 
Process created 
Getting pipes... 
Protocol initialised 
Waiting for child to exit... 
Data received 

而且它只是掛起。

如果我取消了pipe_connection_lost方法,輸出如下:

$ python3.5 async_test.py 
Event loop started 
Process created 
Getting pipes... 
Protocol initialised 
Waiting for child to exit... 
Data received 
Pipe connection lost for the following reason: 
None 

而且仍在進程掛起。我認爲發生的是由於某種原因,子進程(get_rand.py)關閉了管道(如上面的輸出所示),但未終止,因此父節點可以從yield from exit_future開啓。我真的不明白這種行爲背後的原因,考慮到我的代碼大部分都是從python文檔中的示例複製粘貼的。

回答