1. 程式人生 > >python常用系統函式方法與模組

python常用系統函式方法與模組

python常用系統函式方法與模組

python基礎語法總結(一)-- python型別轉換函式+檔案讀寫

python基礎語法總結(二)-- 函式function

python基礎語法總結(三)-- 數與字串

python基礎語法總結(四)-- list列表

python基礎語法總結(五)-- 字典dic + 元組tuple

python基礎語法總結(六)-- python類與OOP面向物件特性


目錄

系統內建函式

sys模組

os模組

os.path

this模組

idle工具


系統內建函式

最基礎、常用的函式方法,可以不用import任何模組就能使用

'''系統常用內建函式'''
help(len)               #help函式,檢視某個函式的具體用法,列印方法定義時的註釋(方法定義時下面第一行的註釋)
callable(len)           #檢視一個obj是不是可以像函式一樣呼叫,本例:True

repr(sys)               #得到obj的表示字串,可以利用這個字串eval重建該物件的一個拷貝
vars(sys)               #返回一個object的屬性和方法。結果為字典型別dictionary
dir(sys)                #作用在類的物件obj上,則可以檢視obj的屬性以及方法,結果為list
dir(1)                          #可以看到1有abs、add、reduce等各種方法
eval("1/3")             #表示合法的python表示式,返回這個表示式的執行結果,本例:0.3333333333333333

locals()                #返回一個區域性name space,用dictionary表示
globals()               #返回一個全域性name space,用dictionary表示
type(sys)               #檢視一個obj的型別
isinstance(obj,cls)         #檢視obj是不是cls的instance
issubclass(subcls,supcls)   #檢視subcls是不是supcls的子類


# 檢查屬性和方法是否存在
hasattr(sys,"exit")     #檢視一個obj是否有某個屬性或者方法,本例:True
hasattr(sys,"abc")      #本例:False

# 得到get屬性和方法
func_exit = getattr(sys,"exit")             #得到一個obj的屬性或者方法
func_exit()                                 #實際執行了sys的exit()方法

# 重寫set屬性和方法
setattr(sys,"api_version","abc")        #為一個obj的屬性或者方法設定新值
print(sys.api_version)                      #控制檯輸出:abc,而不是之前的:1013

def new_exit():                             #準備工作:定義一個新的方法 new_exit()
    print("execute!")
setattr(sys,"exit",new_exit)            # 重寫了sys.exit()方法,改為列印了execcute!的新方法
sys.exit()                                  # 本例:列印臺輸出'execcute!',沒有執行退出操作

# 刪除 delete屬性和方法
delattr(sys,"exit")                     #刪除obj對應的屬性或方法
sys.exit()                                  #本例:提示exit()方法不存在

 

sys模組

'''sys常用'''
import sys
sys.argv                #是一個list,包含本次python啟動時,附帶的所有命令列引數.
sys.stdout
sys.stdin
sys.stderr              #分別表示標準輸入輸出,錯誤輸出的檔案物件.
sys.stdin.readline()    #從標準輸入讀一行
sys.stdout.write("a")   #螢幕輸出a
sys.exit(exit_code)     #退出程式
sys.modules             #是一個dictionary,表示系統中所有可用的module
sys.platform            #得到執行的作業系統環境
sys.path                #是一個list,指明所有查詢module,package的路徑.相當於java的classPath

 

os模組

os模組主要是與作業系統的互動,包括獲取當前使用者、管理員許可權、資料夾、檔案等許可權的修改

''' os  作業系統相關的呼叫和操作  '''
import os
os.environ              # 一個dictionary 包含環境變數的對映關係 os.environ["HOME"] 可以得到環境變數HOME的值
os.chdir(dir)           # 改變當前目錄 os.chdir('d:\outlook') 注意windows下用到轉義
os.getcwd()             # 得到當前目錄
#os.getegid()            # 得到有效組id os.getgid() 得到組id
#os.getuid()             # 得到使用者id os.geteuid() 得到有效使用者id
#os.setegid os.setegid() os.seteuid() os.setuid()
#os.getgruops()          #得到使用者組名稱列表
os.getlogin()           #得到使用者登入名稱
os.getenv('JAVA_HOME')      #得到環境變數
os.putenv()                 # 設定環境變數
os.umask()                  # 設定umask
os.system('cmd')            # 利用系統呼叫,執行cmd命令



# os舉例
os.mkdir('C:/123/')                             # 建立資料夾
os.system("echo 'hello' > C:/a.txt")            # 執行系統命令,本例:在a.txt檔案中寫入hello
os.listdir("C:/Users")                          # 列出資料夾下的檔名
os.rename('C:/a.txt','C:/b.txt')                # 重新命名
os.remove('C:/b.txt')                           # 刪除檔案
os.rmdir('C:/123')                              # 刪除資料夾

 

os.path

## os.path
os.path.abspath("1.txt")                        # 當前目錄下的某個檔案路徑,本例:E:\\WorkSpace\\Python\\BasicDemo\\1.txt(我的專案所在)
os.path.split(os.getcwd())                      # 用於分開一個目錄名稱中的目錄部分和檔名稱部分。本例: ('E:\\WorkSpace\\Python', 'BasicDemo')
os.path.join(os.getcwd(), os.pardir, 'a', 'a.doc')  #全成路徑名稱. 本例:E:\\WorkSpace\\Python\\BasicDemo\\..\\a\\a.doc
os.pardir                                       # 表示當前平臺下上一級目錄的字元 ..
os.path.getctime("C:/b.txt")                    #返回檔案或資料夾的ctime(建立時間)時間戳, 本例:1544406856.9305992
os.path.exists(os.getcwd())                     # 判斷檔案是否存在
os.path.expanduser('~/dir')                     # 把~擴充套件成使用者根目錄
os.path.expandvars('$PATH')                     # 擴充套件環境變數PATH
os.path.isfile(os.getcwd())                     # 判斷是否是檔名
os.path.isdir('C:/123')                         # 判斷是否是目錄,1是0否
os.path.islink('C:/a.txt')                      # 是否是符號連線 windows下不可用
os.path.ismout(os.getcwd())                     # 是否是檔案系統安裝點 windows下不可用
os.path.samefile(os.getcwd(), '/home/huaying')  # 看看兩個檔名是不是指的是同一個檔案
os.path.walk('/home/huaying', test_fun, "a.c")  # 遍歷資料夾下所有檔案,並進行處理,用法複雜,具體可百度

 

this模組

this模組沒有什麼實際作用,只是執行時,會打印出python的語言編寫規範,給初學者以指導

import this

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

 

idle工具

在cmd視窗或linux命令列,輸入idle回車執行時,會開啟python自帶的IDE開發環境,可以在其中編寫python程式碼