如何让Lua脚本等待yt-dlp完成下载及--recode编码后再执行?
Lua脚本等待yt-dlp下载与编码全部完成的同步方案
问题描述
使用Lua调用yt-dlp执行下载并转码MP4时,os.execute仅等待下载阶段完成就返回,导致后续代码(如print("End"))在转码操作尚未结束时就执行。简化代码如下:
local command = "yt-dlp.exe --recode mp4 <URL>" os.execute(command) print("End")
无效尝试
曾尝试通过轮询系统进程列表检查ffmpeg是否存在来判断转码完成,但该方案不生效,代码如下:
var = "yt-dlp.exe --recode mp4 <URL>" os.execute(var) -- 等待转码完成 local recode_done = false while not recode_done do local handle = io.popen("tasklist /FI \"IMAGENAME eq ffmpeg.exe\"") local result = handle:read("*a") handle:close() if not result:find("ffmpeg.exe") then recode_done = true end os.execute("timeout /t 1 >nul") end print("End")
有效解决方法
方法一:通过start /wait强制等待所有子进程完成
在Windows环境下,使用cmd /c start /wait包裹yt-dlp命令,强制命令行等待yt-dlp及其调用的ffmpeg转码进程全部结束后再返回:
local command = 'cmd /c start /wait yt-dlp.exe --recode mp4 <URL>' os.execute(command) print("End")
方法二:利用yt-dlp的--exec参数标记转码完成
让yt-dlp在转码完成后创建一个临时标记文件,Lua脚本轮询该文件是否存在来判断转码结束:
local temp_mark = "recode_complete.tmp" -- 先清理旧的标记文件 os.execute(string.format("del %s 2>nul", temp_mark)) -- 配置yt-dlp完成转码后生成标记文件 local command = string.format( 'yt-dlp.exe --recode mp4 --exec "echo completed > %s" <URL>', temp_mark ) os.execute(command) -- 等待标记文件出现 local is_done = false while not is_done do local file_handle = io.open(temp_mark, "r") if file_handle then file_handle:close() is_done = true -- 清理标记文件 os.execute(string.format("del %s", temp_mark)) else -- 每秒检查一次 os.execute("timeout /t 1 >nul") end end print("End")
方法三:确保yt-dlp自身等待转码完成
部分场景下yt-dlp可能因配置或版本问题提前退出,可添加--no-post-overwrites参数(避免因文件覆盖逻辑提前结束),并确保使用最新版本的yt-dlp:
local command = "yt-dlp.exe --recode mp4 --no-post-overwrites <URL>" os.execute(command) print("End")
内容的提问来源于stack exchange,提问作者Tormy Van Cool
相关产品推荐
相关产品推荐

