You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Telegram Bot异步子进程问题:视频编辑阻塞与执行异常

Telegram Bot异步实现中视频编辑的阻塞与文件不存在问题解决

问题根源分析

  1. 同步实现的阻塞问题:之前用subprocess.run同步执行编辑脚本,会直接阻塞整个Bot的事件循环,导致其他请求无法处理,直到编辑完成。
  2. 异步实现的文件不存在问题:
    • 调用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:54:58