io.popen - 如何等待流程在Lua完成?

问题描述 投票:12回答:1

我必须在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")

我们将不胜感激。

lua popen
1个回答
20
投票

如果您使用标准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.
© www.soinside.com 2019 - 2024. All rights reserved.