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

Colab下载完成后自行停止,未执行后续转码代码的问题排查

问题排查与解决方案

核心问题分析

你的代码存在两个关键问题导致后续转码、移动步骤未执行:

  1. 下载循环条件错误:原代码等待种子进入seeding状态,但多数公开种子下载完成后因缺少peer无法进入播种状态,会卡在finished状态,导致循环无限执行(你看到的"任务完成"实际是循环内的下载完成提示,代码并未走到后续逻辑)。
  2. 文件匹配范围不足:glob.glob('/content/*')仅匹配/content根目录的文件,若种子包含目录结构,下载的文件会存放在子文件夹中,无法被匹配到。

修正后的完整代码

from google.colab import drive
drive.mount('/content/drive')

!apt-get install python3-libtorrent
!pip install lbry-libtorrent
!apt-get install ffmpeg

import libtorrent as lt
import os
import glob
import shutil
import subprocess

params = {
    'save_path': '/content/',
    'storage_mode': lt.storage_mode_t(2),
}

link = 'magnet_link'

ses = lt.session()
handle = lt.add_magnet_uri(ses, link, params)

import time

print('Downloading metadata...')
while not handle.has_metadata():
    time.sleep(1)

print('Starting download...')
# 修正循环条件:等待下载完成(进度100% 或 状态为finished/seeding)
while handle.status().progress < 1.0 or handle.status().state in [lt.torrent_status.downloading, lt.torrent_status.checking]:
    s = handle.status()
    state_str = ['queued', 'checking', 'downloading metadata', 'downloading', 'finished', 'seeding', 'allocating']
    print('%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d) %s' % (
        s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers, state_str[s.state]))
    time.sleep(5)

# 释放libtorrent对文件的占用,避免转码时无法读取
ses.remove_torrent(handle)

print('Download complete, starting conversion...')

# Convert videos to 360p using FFmpeg
if not os.path.exists('/content/converted'):
    os.makedirs('/content/converted')

# 递归匹配所有子文件夹中的视频文件
for file in glob.glob('/content/**/*', recursive=True):
    # 跳过目录,只处理文件
    if not os.path.isfile(file):
        continue
    if file.endswith(('.mkv', '.avi', '.mov', '.wmv', '.mp4')):
        output_file = '/content/converted/' + os.path.splitext(os.path.basename(file))[0] + '.mp4'
        # 执行转码并捕获错误信息,方便调试
        result = subprocess.run(
            ['ffmpeg', '-i', file, '-vf', 'scale=640:360', '-threads', '0', '-y', output_file],
            capture_output=True, text=True
        )
        if result.returncode == 0:
            print(f"转码完成: {file} -> {output_file}")
        else:
            print(f"转码失败 {file}: {result.stderr}")

# Move converted files to Google Drive
drive_dir = '/content/drive/My Drive/Torrents'
if not os.path.exists(drive_dir):
    os.makedirs(drive_dir)

for file in glob.glob('/content/converted/*'):
    try:
        shutil.move(file, drive_dir)
        print(f"已移动文件: {file} -> {drive_dir}")
    except Exception as e:
        print(f"移动失败 {file}: {str(e)}")

关键修改点说明

  • 修正循环退出逻辑:不再等待seeding,只要下载进度达到100%且状态不在下载/检查中,就退出循环,确保后续代码能执行。
  • 释放文件锁:添加ses.remove_torrent(handle),让libtorrent释放下载文件的占用,避免FFmpeg无法读取文件。
  • 递归匹配文件:使用glob.glob('/content/**/*', recursive=True)匹配所有子文件夹中的视频文件,覆盖种子带目录结构的情况。
  • 错误捕获与日志:转码和移动步骤添加错误信息打印,方便排查执行失败的具体原因。

内容的提问来源于stack exchange,提问作者zircon98

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:23:14