如何准备一个异步生成器函数作为另一个函数的参数?

2024-10-01 11:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

如何准备一个异步生成器函数作为另一个函数的参数?你知道吗

当我使用loop.run\ in\执行器要将普通函数包装为异步任务,其参数之一是生成器(dataof requests.post

import asyncio, os, sys, subprocess, aionotify, tempfile

class CommandDelegate():
    def _yielding_log(self, pid, stdout_file):
        w = aionotify.Watcher()
        w.setup(loop)
        if type(stdout_file) not in [str, bytes]:
            stdout_file = stdout_file.name
        try:
            w.watch(stdout_file, aionotify.Flags.MODIFY | aionotify.Flags.CLOSE_WRITE)
            with open(stdout_file, 'r') as the_file:
                while True:
                    line = the_file.readline()
                    if line != '':
                        yield line
                    else:
                        if os.path.exists('/proc/' + pid):
                            break
                        evt = w.get_event()
                        parsed_flags = aionotify.Flags.parse(evt.flags)
                        if aionotify.Flags.MODIFY in parsed_flags:
                            continue
                        if aionotify.Flags.CLOSE_WRITE in parsed_flags:
                            break
        finally:
            w.close()


    def _exec_command(self, job_dir, order, shell_command):
        stdout_file = tempfile.NamedTemporaryFile(prefix='stdout', suffix='log', delete=False)
        cmd = shlex.split(shell_command)
        ps = subprocess.Popen(args=cmd, stdout=stdout_file, cwd=job_dir, stderr=stdout_file)
##### WHAT TO DO HERE
        loop.run_in_executor(None, requests.post, 'upstream', data=
                             WHAT__TO__DO__HERE(self._yielding_log(stdout_file))
                             )
        return ps.wait() != 0

Tags: 函数inselflooplog参数ifstdout