Lua的os.execute返回值是什么?

64
能否从Lua的本地变量中读取以下内容?
local t = os.execute("echo 'test'")
print(t)

我只想实现这个功能:每当 os.execute 返回任何值时,我希望能在Lua中使用它,例如echo 'test'将在bash命令行中输出test - 是否可能获取返回的值(这种情况下为test)到Lua本地变量中?

5个回答

119

你可以使用io.popen()代替。它会返回一个文件句柄,你可以用它来读取命令的输出。类似下面的代码可能会起作用:

local handle = io.popen(command)
local result = handle:read("*a")
handle:close()

请注意,这将包括命令发出的尾随换行符(如果有的话)。


1
收到此消息:“不支持'popen'”。 - Cyclone
@Cyclone:根据手册,“此函数依赖于系统,不是所有平台都可用”。你在哪个平台上尝试这个功能?考虑到可用的函数,我唯一能想到的解决方法是使用os.execute(),但将标准输出重定向到已知的临时文件,然后之后再读取临时文件。 - Lily Ballard
我正在使用FreeBSD 8.2。关于你的第二个建议 - 你能给我一些它应该是什么样子的例子吗?而且性能如何?这需要大量的读写操作。 - Cyclone
7
@Cyclone: 类似这样的代码 os.execute(command .. " >/tmp/foo") (其中 /tmp/foo 被替换为一个实际的独特路径,您可以按您想要的任何方式计算)。 - Lily Ballard
我能否做与问题相反的事情?在操作系统 shell 中返回 Lua 值。 - Unknow0059
尝试使用local handle = io.popen([[echo wifiap> \\.\COM78]]),但这可能不是从COM端口读取响应的正确方法。 - Sany

4
function GetFiles(mask)
   local files = {}
   local tmpfile = '/tmp/stmp.txt'
   os.execute('ls -1 '..mask..' > '..tmpfile)
   local f = io.open(tmpfile)
   if not f then return files end  
   local k = 1
   for line in f:lines() do
      files[k] = line
      k = k + 1
   end
   f:close()
   return files
 end

3
如果您的系统支持,io.popenos.execute更适合此用例。后者仅返回退出状态而不是输出。
-- runs command on a sub-process.
local handle = io.popen('cmd')
-- reads command output.
local output = handle:read('*a')
-- replaces any newline with a space
local format = output:gsub('[\n\r]', ' ')

工作示例:

local handle = io.popen('date +"%T.%6N"')
local output = handle:read('*a')
local time = output:gsub('[\n\r]', ' ')
handle:close()
print(time .. 'DEBUG: Time recorded when this event happened.')

祝福你,善良的陌生人。 - Jose V

-6
Lua的os.capture会返回所有标准输出,因此它将被返回到该变量中。
示例:
local result = os.capture("echo hallo")
print(result)

打印:

hallo

3
我认为这种方法不属于os模块。http://www.lua.org/manual/5.3/manual.html#6.9 - rodvlopes
2
这需要从此答案中获取代码片段,并使用popen。 - HaoZeke

-20

抱歉,这是不可能的。 如果回显程序成功退出,则会返回0。这个返回码就是os.execute()函数获取并返回的。

if  0 == os.execute("echo 'test'") then 
    local t = "test"
end

这是一种获取你想要的方式,希望能对你有所帮助。

另一个获取函数返回代码的提示是Lua参考文献。 Lua-Reference/Tutorial


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接