Quick and Dirty way to grab the output from command line programs, the example below prints all the environment variables, but it could be used to capture directory listings or ipconfig output.
Requires: None
Code
-
local Hnd, ErrStr = io.popen("set") if Hnd then for Line in Hnd:lines() do print(Line) end -- for Line Hnd:close() else print(ErrStr) end
Version 2
Another cleaner option which avoids the “command line flash” is to use Luacom and write the information to a temporary file.
-
local function readAll(file) local f = assert(io.open(file, "rb")) local content = f:read("*all") f:close() return content end local sTmpFile = os.tmpname()..'.txt' print(sTmpFile) -- Windows Version local sCmd = 'cmd /c ver > '..sTmpFile Shell = luacom.CreateObject("WScript.Shell") Shell:Run (sCmd, 0, true) sVersion = readAll(sTmpFile) print(sVersion) os.remove(sTmpFile)
Note the Shell:Run parameters are
- 1. The command to run
- 0 = hide window
- true = wait for command to finish before continuing