gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:40:26 27 4
gpt4 key购买 nike

我必须使用 io.popen在 Lua 中运行一个带有命令行参数的可执行文件。
如何在 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,您的代码看起来有点奇怪。我不完全确定 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.

关于lua - io.popen - 如何在 Lua 中等待进程完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239317/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com