io.popen - 如何在 Lua 中等待进程完成? [英] io.popen - how to wait for process to finish in Lua?

查看:146
本文介绍了io.popen - 如何在 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 FilesXYZ.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, '[

]+', ' ') 
  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆