Python Telegram Bot异步子进程问题:视频编辑阻塞与执行异常
Telegram Bot异步实现中视频编辑的阻塞与文件不存在问题解决
问题根源分析
- 同步实现的阻塞问题:之前用
subprocess.run同步执行编辑脚本,会直接阻塞整个Bot的事件循环,导致其他请求无法处理,直到编辑完成。 - 异步实现的文件不存在问题:
- 调用
edit_video时未加await,协程未被等待就继续执行后续的send_video,此时编辑脚本可能还没执行,甚至视频下载都没完成。 edit_video内部仍使用同步的subprocess.run,即使加了await,依然会阻塞事件循环,同时没确保子进程执行完成就继续后续操作。
- 调用
解决方案
1. 异步执行子进程脚本
把edit_video里的同步子进程调用改为asyncio的异步子进程方法,避免阻塞事件循环,同时等待子进程执行完成:
import asyncio async def edit_video(title, input_path, file_hash, user_id): # 异步启动编辑子进程 proc = await asyncio.create_subprocess_exec( "python", "./editor.py", profile, title, input_path, file_hash, str(user_id), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) # 等待子进程执行完成并获取输出 stdout, stderr = await proc.communicate() # 检查子进程执行状态,处理错误 if proc.returncode != 0: print(f"编辑脚本执行错误: {stderr.decode('utf-8')}") raise RuntimeError(f"视频编辑失败,错误信息: {stderr.decode('utf-8')}")
2. 确保所有异步操作都被等待
- 调用
edit_video时必须加await,保证编辑完成后再执行发送操作。 - 确保视频下载步骤是异步且已被
await的(你的下载逻辑必须是异步实现并等待完成,否则文件还没生成就调用编辑会报错)。
修改调用代码:
# 先确保视频下载完成(此处替换为你的异步下载代码,必须加await) # await async_download_video(chat_id, profile, file_hash, download_folder) # 等待视频编辑完成 await edit_video(message_text, f"{download_folder}/{str(chat_id)}/{profile}/{file_hash}.mp4", file_hash, chat_id) download_path = f"./exported/{str(chat_id)}/{profile}/{file_hash}.mp4" # 发送前检查文件是否存在,避免报错 import os if os.path.exists(download_path): await bot.send_video(chat_id=chat_id, video=open(download_path, 'rb')) else: await bot.send_message(chat_id=chat_id, text="视频编辑失败,未生成目标文件")
3. 额外优化建议
- 给下载和编辑操作添加超时处理,避免长时间卡住。
- 对文件路径使用
pathlib库处理,避免字符串拼接的路径错误。 - 添加日志记录,方便排查下载或编辑过程中的问题。
内容的提问来源于stack exchange,提问作者Pady
相关产品推荐
相关产品推荐

