Read console output realtime in lua

回眸只為那壹抹淺笑 提交于 2019-12-23 12:52:35

问题


How can I manage to periodically read the output of a script while it is running?

In the case of youtube-dl, it sends download information (progress/speed/eta) about the video being downloaded to the terminal.

With the following code I am able to capture the total result of the scripts output (on linux) to a temporary file:

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"))

Instead of waiting for the script to complete and writing all the data at the end, I would like able to capture "snapshots" of the latest information that youtube-dl has sent to the terminal.

My overall goal is to capture the download information in order to design a progress bar using Iup.

If there are more intelligent ways of capturing download information I will be happy to take advice as well.

Regardless, if it is possible to use io.popen(), os.execute(), or other tools in such a way I would still like to know how to capture the real time console output.


回答1:


This works fine both on Windows and Linux. Lines are displayed in real-time.

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

UPD :
If previous code didn't work try the following (as dualed suggested):

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()


来源:https://stackoverflow.com/questions/17636812/read-console-output-realtime-in-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!