Get back the output of os.execute in Lua

前端 未结 3 1171
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 00:27

When I do an \"os.execute\" in Lua, a console quickly pops up, executes the command, then closes down. But is there some way of getting back the console output only using th

3条回答
  •  臣服心动
    2020-12-03 01:15

    If you have io.popen, then this is what I use:

    function os.capture(cmd, raw)
      local f = assert(io.popen(cmd, 'r'))
      local s = assert(f:read('*a'))
      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
    

    If you don't have io.popen, then presumably popen(3) is not available on your system, and you're in deep yoghurt. But all unix/mac/windows Lua ports will have io.popen.

    (The gsub business strips off leading and trailing spaces and turns newlines into spaces, which is roughly what the shell does with its $(...) syntax.)

提交回复
热议问题