io.popen - 如何在 Lua 中等待进程完成?
我必须在 Lua 中使用 io.popen 来运行带有命令行参数的可执行文件。 如何在 Lua 中等待进程完成以便捕获预期输出?
local command = "C:\Program Files\XYZ.exe /all"
hOutput = io.popen(command)
print(string.format(""%s", hOutput))
假设可执行文件是 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")
我们将不胜感激您的帮助。
I have to use io.popen
in Lua to run an executable which takes a command line argument.
How to wait for a process to finish in the Lua so that expected output can be captured?
local command = "C:\Program Files\XYZ.exe /all"
hOutput = io.popen(command)
print(string.format(""%s", hOutput))
Suppose the executable is XYZ.exe which needs to be called with command line argument /all
.
Once io.popen(command)
gets executed, the process will return some string which needs to be printed.
My code snippet:
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+
Your help will be appreciated.
, '')
s = string.gsub(s, '[\n\r]+', ' ')
return s
end
local command = capture("C:\Tester.exe /all")
Your help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用标准 Lua,您的代码看起来有点奇怪。我不完全确定有关超时或平台依赖性的 io.popen 语义,但以下内容至少在我的机器上有效。
If you are using standard Lua your code looks a bit odd. I am not completely sure about
io.popen
semantics regarding timeouts or platform dependencies, but the following works at least on my machine.我最终用这个来捕获相对较大的输出:
I ended up with this for capturing relatively big output: