我必须io.popen在Lua中运行一个可执行文件,它接受一个命令行参数.如何等待流程在Lua中完成,以便捕获预期的输出?
local command = "C:\Program Files\XYZ.exe /all"
hOutput = io.popen(command)
print(string.format(""%s", hOutput))
Run Code Online (Sandbox Code Playgroud)
假设可执行文件是XYZ.exe,需要使用命令行参数调用/all.
一旦io.popen(command)执行,该过程将返回一些需要打印的字符串.
我的代码片段:
function capture(cmd, raw)
local f = assert(io.popen(cmd, 'r'))
-- wait(10000);
local s = assert(f:read('*a'))
Print(string.format("String: %s",s ))
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
local command = capture("C:\Tester.exe /all")
Run Code Online (Sandbox Code Playgroud)
我们将不胜感激.
pon*_*zao 21
如果您使用标准Lua,您的代码看起来有点奇怪.我不完全确定io.popen有关超时或平台依赖性的语义,但以下工作至少在我的机器上有效.
local file = assert(io.popen('/bin/ls -la', 'r'))
local output = file:read('*all')
file:close()
print(output) -- > Prints the output of the command.
Run Code Online (Sandbox Code Playgroud)