5

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.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
logen
  • 53
  • 1
  • 4

1 Answers1

4

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()
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
  • This wouldn't work as well for binary data though. First because you probably won't see that many `\n` in it and second because it will filter them and `\r\n`. It's better to read a specified max buffer size like `pipe:read(4*1048576)` – dualed Jul 14 '13 at 21:08
  • @dualed - Yes, even for human-readable pure-text output reading whole lines may be not suitable for getting current position of progress bar displaying by appending one star at a time. – Egor Skriptunoff Jul 14 '13 at 21:23
  • @EgorSkriptunoff The ping test worked, however trying it with youtube-dl (with print) I've discovered that it hangs right before the progress information shows up, it waits here until it is complete and then just prints the last bit of progress, so I need to find a different way to solve my problem. – logen Jul 15 '13 at 03:17
  • @logen see my comment above, and better not use print (it appends `\n`) but `file:write()` – dualed Jul 15 '13 at 05:47