【问题标题】:io.popen - how to wait for process to finish in Lua?io.popen - 如何在 Lua 中等待进程完成?
【发布时间】:2011-07-11 11:48:45
【问题描述】:

我必须在 Lua 中使用io.popen 来运行带有命令行参数的可执行文件。 如何在 Lua 中等待进程完成以便捕获预期的输出?

  local command = "C:\Program Files\XYZ.exe /all"

  hOutput = io.popen(command)
  print(string.format(""%s", hOutput))

假设可执行文件是需要使用命令行参数/all 调用的XYZ.exe。

一旦io.popen(command)被执行,进程将返回一些需要打印的字符串。

我的代码sn-p:

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

您的帮助将不胜感激。

【问题讨论】:

  • 我的代码不知何故无法正常工作
  • 函数捕获(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本地命令 = capture("C:\Tester.exe /all")

标签: lua popen


【解决方案1】:

如果您使用的是标准 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.

【讨论】:

  • 你能解释一下,为什么你需要assert吗?
  • @rubo77,我有一段时间没有使用 Lua,但根据快速测试,我认为 assert 在这种情况下根本没有用,因为 io.popen 似乎又回来了一个对象,即使有错误。
【解决方案2】:

我最终用这个来捕获相对较大的输出:

io.stdout:setvbuf 'no' 
local file = assert(io.popen('/bin/ls -la', 'r'))
file:flush()  -- > important to prevent receiving partial output
local output = file:read('*all')
file:close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-24
    • 2012-03-16
    • 2010-11-06
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多