前言#
今天這個函數(shù)說起來應(yīng)該是有兩重身份的,首先它是一個和文件相關(guān)的函數(shù),另外他又是一個可以執(zhí)行命令的函數(shù),這一點和之前講過的函數(shù)os.execute()
有點相似,接下來我們就一起來看一下這個函數(shù)的用法。
內(nèi)容#
io.popen()##
- 原型:io.popen ([prog [, mode]])
- 解釋:在額外的進程中啟動程序
prog
,并返回用于prog的文件句柄。通俗的來說就是使用這個函數(shù)可以調(diào)用一個命令(程序),并且返回一個和這個程序相關(guān)的文件描述符,一般是這個被調(diào)用函數(shù)的輸出結(jié)果,這個文件打開模式由參數(shù)mode
確定,有取值"r"
和"w"
兩種,分別表示以讀、寫方式打開,默認(rèn)是以讀的方式。
Usage##
- 首先新建一個文件popentest.lua然后編寫以下代碼:
-- 打開文件(這個文件保存的是命令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()
- 運行結(jié)果
io_popen.png
總結(jié)#
- 使用這個函數(shù)需要的注意的是這個函數(shù)是依賴于操作系統(tǒng)的,也就是說并不是所有的系統(tǒng)都可以返回正確的結(jié)果。
- 讀取文件內(nèi)容之前最好檢測一下文件描述符的有效性,盡可能的避免程序出錯。
- 從運行的結(jié)果來看,使用這個函數(shù)來執(zhí)行命令,和直接在命令行界面執(zhí)行命令的結(jié)果上一樣的,只不過使用函數(shù)這種方式的結(jié)果保存在文件中。