5

如何在脚本运行时定期读取脚本的输出?

对于 youtube-dl,它会将有关正在下载的视频的下载信息(进度/速度/eta)发送到终端。

使用以下代码,我可以将脚本输出(在 linux 上)的总结果捕获到一个临时文件中:

tmpFile = io.open("/tmp/My_Temp.tmp", "w+")
f = io.popen("youtube-dl http://www.youtube.com/watch?v=UIqwUx_0gJI", 'r')

tmpFile:write(f:read("*all"))

我希望能够捕获 youtube-dl 发送到终端的最新信息的“快照”,而不是等待脚本完成并在最后写入所有数据。

我的总体目标是捕获下载信息,以便使用 Iup 设计进度条。

如果有更智能的方法来捕获下载信息,我也很乐意接受建议。

无论如何,如果可以以这种方式使用 io.popen()、os.execute() 或其他工具,我仍然想知道如何捕获实时控制台输出。

4

1 回答 1

4

这在 Windows 和 Linux 上都可以正常工作。线条实时显示。

local pipe = io.popen'ping google.com'
for line in pipe:lines() do
    print(line)
end
pipe:close()

UPD:
如果以前的代码不起作用,请尝试以下操作(如双重建议):

local pipe = io.popen'youtube-dl with parameters'
repeat
    local c = pipe:read(1)
    if c then 
        -- Do something with the char received
        io.write(c)  io.flush()
    end
until not c
pipe:close()
于 2013-07-14T10:44:55.037 回答