前言#
今天這個(gè)函數(shù)說起來應(yīng)該是有兩重身份的幕垦,首先它是一個(gè)和文件相關(guān)的函數(shù)投慈,另外他又是一個(gè)可以執(zhí)行命令的函數(shù)遍希,這一點(diǎn)和之前講過的函數(shù)os.execute()
有點(diǎn)相似授霸,接下來我們就一起來看一下這個(gè)函數(shù)的用法锁摔。
內(nèi)容#
io.popen()##
- 原型:io.popen ([prog [, mode]])
- 解釋:在額外的進(jìn)程中啟動(dòng)程序
prog
廓旬,并返回用于prog的文件句柄。通俗的來說就是使用這個(gè)函數(shù)可以調(diào)用一個(gè)命令(程序)谐腰,并且返回一個(gè)和這個(gè)程序相關(guān)的文件描述符孕豹,一般是這個(gè)被調(diào)用函數(shù)的輸出結(jié)果,這個(gè)文件打開模式由參數(shù)mode
確定怔蚌,有取值"r"
和"w"
兩種巩步,分別表示以讀、寫方式打開桦踊,默認(rèn)是以讀的方式椅野。
Usage##
- 首先新建一個(gè)文件popentest.lua然后編寫以下代碼:
-- 打開文件(這個(gè)文件保存的是命令dir的結(jié)果)
local myfile = io.popen("dir", "r")
if nil == myfile then
print("open file for dir fail")
end
print("\n======commond dir result:")
-- 讀取文件內(nèi)容
for cnt in myfile:lines() do
print(cnt)
end
-- 關(guān)閉文件
myfile:close()
local secondfile = io.popen("ipconfig")
if nil == secondfile then
print("open file for ipconfig fail")
end
print("\n======commond ipconfig result:")
-- 讀取文件內(nèi)容
local content = secondfile:read("*a")
print(content)
-- 關(guān)閉文件
secondfile:close()
- 運(yùn)行結(jié)果
總結(jié)#
- 使用這個(gè)函數(shù)需要的注意的是這個(gè)函數(shù)是依賴于操作系統(tǒng)的,也就是說并不是所有的系統(tǒng)都可以返回正確的結(jié)果。
- 讀取文件內(nèi)容之前最好檢測(cè)一下文件描述符的有效性竟闪,盡可能的避免程序出錯(cuò)离福。
- 從運(yùn)行的結(jié)果來看,使用這個(gè)函數(shù)來執(zhí)行命令炼蛤,和直接在命令行界面執(zhí)行命令的結(jié)果上一樣的妖爷,只不過使用函數(shù)這種方式的結(jié)果保存在文件中。