关于 asyncio - Subprocess 的 Python 文档说:
该
communicate()和wait()方法不采取超时参数:使用wait_for()功能
对communicate()using施加超时非常容易wait_for(),但是我找不到从中断的communicate()调用中检索部分结果的方法,并且后续调用communicate()也不会返回丢失的部分。
示例脚本:
#! /usr/bin/env python3
import asyncio
async def communicate_short(loop):
p = await asyncio.create_subprocess_exec('ping', '127.0.0.1', '-n', '4', stdout=asyncio.subprocess.PIPE)
# For Linux: use '-c' instead of '-n'
try:
# 2 seconds timeout
res = await asyncio.wait_for(p.communicate(), 2)
except asyncio.TimeoutError as e:
# After timeout happens:
# How do I get the subprocess's STDOUT up to this point?
try:
print(res[0].decode('utf-8')) …Run Code Online (Sandbox Code Playgroud) 在编写 Python 异步程序时,通常会有一个异步函数同时运行许多调用。我想为这个函数添加一些日志记录,但是来自不同调用的日志记录输出将交错,使其难以跟踪。我目前的解决方案是以某种方式为每次调用创建一个唯一的名称,并每次记录该名称,如下所示:
async def make_request(args):
logger = logging.getLogger('myscript.request')
log_name = unique_name()
logger.debug('[%s] making request with args %r', log_name, args)
response = await request(args)
logger.debug('[%s] response: %r', log_name, response)
Run Code Online (Sandbox Code Playgroud)
但是,必须log_name输入每个日志记录调用会很快变得很累。为了保存这些击键,我想出了一个不同的解决方案,为每次调用创建一个具有唯一名称的新记录器:
async def make_request(args):
logger = logging.getLogger(f'myscript.request.{unique_name()}')
logger.debug('making request with args %r', args)
response = await request(args)
logger.debug('response: %r', response)
Run Code Online (Sandbox Code Playgroud)
这种方法有什么缺点吗?我唯一能想到的是创建一个新的记录器可能很昂贵,但事实真的如此吗?有什么我没有看到的陷阱吗?