Shell 存取 |
|
[!] VersionNotice:以下程式碼屬於較舊的 Lua 版本,Lua 4。某些部分無法如在 Lua 5 中執行。
這從行程中讀取輸出,經由管線。有一種方法讓這個在視窗上也能執行(參閱 PipesOnWindows,Lua 5.1.2 不需要,見下方說明)。
-- Perform a shell command and return its output -- c: command -- returns -- o: output function shell(c) local input = _INPUT local o, h h = readfrom("|" .. c) o = read("*a") closefile(h) _INPUT = input return o end
Lua 5.0.2 中,我想應類似於
function shell(c) local o, h h = assert(io.popen(c,"r")) o = h:read("*all") h:close() return o end
Lua 5.1.2:io.popen 能在 Windows XP 中執行良好,即使在非 DOS 應用程式中 --AndreasRozek
在命令列實用程式中想要執行的典型作業是處理命令列上給定的每個檔案。以下是一個函數來封裝這個處理程序
-- Process all the files specified on the command-line with function f -- name: the name of the file being read -- i: the number of the argument function processFiles(f) for i = 1, getn(arg) do if arg[i] == "-" then readfrom() else readfrom(arg[i]) end file = arg[i] f(arg[i], i) readfrom() -- close file, if not already closed end end