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

发布于 2024-10-21 08:00:56 字数 758 浏览 2 评论 0原文

我必须在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡莣 2024-10-28 08:00:56

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

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.
南薇 2024-10-28 08:00:56

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

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

I ended up with this for capturing relatively big output:

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文