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")

谢谢您的帮助。

原文链接 https://stackoverflow.com/questions/5239317

点赞
stackoverflow用户206020
stackoverflow用户206020

如果你正在使用标准的Lua,你的代码看起来可能有点奇怪。我不是完全确定关于io.popen超时或平台依赖方面的语义,但以下代码至少在我的机器上可以工作。

local file = assert(io.popen('/bin/ls -la', 'r'))
local output = file:read('*all')
file:close()
print(output) -- > 打印命令的输出。
2011-03-09 08:43:50
stackoverflow用户1964792
stackoverflow用户1964792

我最终使用以下代码来获取相对较大的输出:

io.stdout:setvbuf 'no'
local file = assert(io.popen('/bin/ls -la', 'r'))
file:flush()  -- > 重要的是为了防止接收到部分输出
local output = file:read('*all')
file:close()
2021-11-04 08:40:11