python:类似asyncio.create_subprocess_{shell,exec},但运行函数而不是可执行文件?
这个问题类似于我最近在这里提出的另一个问题(),只是这个问题与python:类似asyncio.create_subprocess_{shell,exec},但运行函数而不是可执行文件?,python,lambda,pipe,fork,python-asyncio,Python,Lambda,Pipe,Fork,Python Asyncio,这个问题类似于我最近在这里提出的另一个问题(),只是这个问题与asyncio世界有关 asyncio.create_subprocess{shell,exec}函数提供了一种方便的方法,可以在子流程中运行可执行文件,并通过启用异步的管道与其stdin、stdout和stderr进行交互。我正在寻找一个类似的过程,该过程将在子流程中运行任意函数,并向其stdin、stdout和stderr提供相同的支持异步IO的管道。例如,假设此假设函数名为asyncio.create_subprocess_la
asyncio
世界有关
asyncio.create_subprocess{shell,exec}
函数提供了一种方便的方法,可以在子流程中运行可执行文件,并通过启用异步的管道与其stdin
、stdout
和stderr
进行交互。我正在寻找一个类似的过程,该过程将在子流程中运行任意函数,并向其stdin
、stdout
和stderr
提供相同的支持异步IO的管道。例如,假设此假设函数名为asyncio.create_subprocess_lambda
。我希望它的工作方式大致如下:
def myfunc(*args, **kwargs):
# does arbitrary things with stdin, stdout, and stderr.
return 0
async def run():
proc = await asyncio.create_subprocess_lambda(
lambda : myfunc('a', 'b', c='d'),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
print(f'[lambda exited with {proc.returncode}]')
if stdout:
print(f'[stdout]\n{stdout.decode()}')
if stderr:
print(f'[stderr]\n{stderr.decode()}')
这将导致在myfunc
函数作为子函数运行时发生fork,并且其stdout
和stderr
输出可通过异步管道在父函数中访问
我知道这样的函数目前还不存在,但我希望有其他的asyncio
方法可以让我用最少的复杂、复杂的代码实现这个功能
提前感谢您的建议。在stdin/stdout/stderr上操作是您与家长沟通的唯一方式吗?如果您可以通过共享队列发送对象,它对您有用吗?子对象是一个使用第三方软件包的函数,其中一些软件包会写入stderr和stdout。除非我重写所有这些附属包,否则我将不得不捕获stdout和stderr。