在lua中读取控制台输出实时 [英] Read console output realtime in lua

查看:3607
本文介绍了在lua中读取控制台输出实时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

使用以下代码,我能够捕获脚本输出(在linux上)的总结果临时文件:

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

不等待脚本完成并写入所有数据像是能够捕获youtube-dl发送到终端的最新信息的快照。

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.

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

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.

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

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.

推荐答案

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

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:

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


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

这篇关于在lua中读取控制台输出实时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆