io.popen-如何在Lua中等待进程完成? [英] io.popen - how to wait for process to finish in Lua?
问题描述
我必须在Lua中使用io.popen
来运行带有命令行参数的可执行文件.
如何等待Lua中的进程完成,以便可以捕获预期的输出?
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))
假定可执行文件是XYZ.exe,需要使用命令行参数/all
进行调用.
Suppose the executable is XYZ.exe which needs to be called with command line argument /all
.
一旦执行io.popen(command)
,该过程将返回一些需要打印的字符串.
Once io.popen(command)
gets executed, the process will return some string which needs to be printed.
我的代码段:
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")
您的帮助将不胜感激.
推荐答案
如果您使用的是标准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.
local file = assert(io.popen('/bin/ls -la', 'r'))
local output = file:read('*all')
file:close()
print(output) -- > Prints the output of the command.
这篇关于io.popen-如何在Lua中等待进程完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!