将子进程与asyncio一起使用时如何不阻塞主线程

时间:2019-12-31 02:59:27

标签: python subprocess python-asyncio

我正在创建从CLI运行的模块。用户选择并运行一个模块。我正在尝试在后台运行一个任务,然后执行另一个任务。理想情况下,当用户运行模块时,它将立即在后台运行任务,从而使他们返回CLI来运行其他模块。

我尝试了多种方法,但是未能在不阻塞线程的情况下使parse_cmd函数在run_cmd函数之后运行。

import subprocess
import asyncio

class test(Module):
    async def run_cmd(self):
        proc = await asyncio.create_subprocess_shell(
            'ls -la', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) # Generally a long-running task
        await proc.wait() # This blocks the thread and does not allow interaction until the process is complete. 

    async def parse_cmd(self):
        print('Process complete. Now parsing result...')
        # Do stuff here

    def run(self):
        ioloop = asyncio.get_event_loop()
        ioloop.run_until_complete(self.run_cmd())
        ioloop.run_until_complete(self.parse_cmd())

0 个答案:

没有答案
相关问题