在Lua中获取os.execute的输出
时间:2020-03-06 14:42:45 来源:igfitidea点击:
当我在Lua中执行" os.execute"时,控制台会迅速弹出,执行命令,然后关闭。但是,是否有某种方法只能使用标准的Lua库来获取控制台输出呢?
解决方案
我不特别了解Lua,但通常可以这样运行命令:
comd >comd.txt 2>&1
捕获comd.txt文件的输出和错误,然后使用语言文件I / O函数读取它。
如果语言本身没有提供捕获标准输出和错误的方式,那我将这样做。
我认为我们想要这个http://pgl.yoyo.org/luai/i/io.popen io.popen。但是它并不总是被编译进来。
如果我们拥有io.popen,那么这就是我所使用的:
function os.capture(cmd, raw) local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() if raw then return s end s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end
如果我们没有io.popen,则大概popen(3)在系统上不可用,并且我们处于酸奶状态。但是所有unix / mac / windows Lua端口都将具有io.popen。