python基礎之模組part2

來源:互聯網
上載者:User

標籤:建立   格式化   nbsp   created   完整   argv   資料   沒有   根據   

sys:

  sys模組不同於os模組,這個是跟Python解譯器打交道的。

sys.argv:返回一個檔案名稱開頭,包含後面輸入內容的 列表 

import sysres = sys.argvprint(res)執行:C:\Users\ldsly>python E:\Python\DAY-13\模組2.py[‘E:\\Python\\DAY-13\\模組2.py‘]C:\Users\ldsly>------------------------------------------------------------------------------import sysres = sys.argvprint(res)username = res[1]passwd = res[2]if username == ‘user‘ and passwd == ‘666‘:    print(‘login‘)執行:C:\Users\ldsly>python E:\Python\DAY-13\模組2.py user 666[‘E:\\Python\\DAY-13\\模組2.py‘, ‘user‘, ‘666‘]loginC:\Users\ldsly>

sys.platform:返回作業系統平台名稱

import sysprint(sys.platform)執行:C:\Users\ldsly>python E:\Python\DAY-13\模組2.pywin32C:\Users\ldsly>

sys.path:返回模組的搜尋路徑,初始化使用Python時的環境變數。

import sysprint(sys.path)執行:C:\Users\ldsly>python E:\Python\DAY-13\模組2.py[‘E:\\Python\\DAY-13‘, ‘D:\\Python\\Python36-32\\python36.zip‘, ‘D:\\Python\\Python36-32\\DLLs‘, ‘D:\\Python\\Python36-32\\lib‘, ‘D:\\Python\\Python36-32‘, ‘D:\\Python\\Python36-32\\lib\\site-packages‘]C:\Users\ldsly>-----------------------------------------------------------添加path:import sysprint(sys.path)sys.path.append(‘E:\Python‘)print(sys.path)執行:C:\Users\ldsly>python E:\Python\DAY-13\模組2.py[‘E:\\Python\\DAY-13‘, ‘D:\\Python\\Python36-32\\python36.zip‘, ‘D:\\Python\\Python36-32\\DLLs‘, ‘D:\\Python\\Python36-32\\lib‘, ‘D:\\Python\\Python36-32‘, ‘D:\\Python\\Python36-32\\lib\\site-packages‘][‘E:\\Python\\DAY-13‘, ‘D:\\Python\\Python36-32\\python36.zip‘, ‘D:\\Python\\Python36-32\\DLLs‘, ‘D:\\Python\\Python36-32\\lib‘, ‘D:\\Python\\Python36-32‘, ‘D:\\Python\\Python36-32\\lib\\site-packages‘, ‘E:\\Python‘]C:\Users\ldsly>

sys.version:擷取Python解譯器的版本。

import sysprint(sys.version)執行:C:\Users\ldsly>python E:\Python\DAY-13\模組2.py3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)]C:\Users\ldsly>

sys.exit():退出程式,程式運行過程中遇見exit就會直接退出程式。

import sysa = 10if a < 5:    print(a)else:     sys.exit()  #條件不成立直接退出程式print(a)  #根據結果顯示並沒有輸出 變數a程式就直接退出了。執行:C:\Users\ldsly>python E:\Python\DAY-13\模組2.pyC:\Users\ldsly>

logging: 日誌模組。

記錄層級:從上到下,預設是warning層級,即只顯示warning層級含warning以下的日誌。

import logginglogging.debug(‘debug message‘)logging.info(‘info message‘)logging.warning(‘warning message‘)logging.error(‘error message‘)logging.critical(‘critical message‘)執行結果:D:\Python\Python36-32\python.exe E:/Python/DAY-13/模組2.pyWARNING:root:warning messageERROR:root:error messageCRITICAL:root:critical messageProcess finished with exit code 0

樣本:使用logging.basicConfig()來定義日誌配置資訊。

import logginglogging.basicConfig(level=logging.DEBUG,       #設定記錄層級                    format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,  #日誌儲存格式                    datefmt=‘%a, %d %b %Y %H:%M:%S‘,    #日誌儲存時間 格式                    filename=r‘E:\Python\DAY-13\test.log‘,  #記錄檔儲存位置                    filemode=‘w‘)    #記錄檔的讀寫入模式logging.debug(‘debug message‘)logging.info(‘info message‘)logging.warning(‘warning message‘)logging.error(‘error message‘)logging.critical(‘critical message‘)執行結果:(目前的目錄位置下產生的記錄檔內容)Thu, 22 Jun 2017 20:44:34 模組2.py[line:59] DEBUG debug messageThu, 22 Jun 2017 20:44:34 模組2.py[line:60] INFO info messageThu, 22 Jun 2017 20:44:34 模組2.py[line:61] WARNING warning messageThu, 22 Jun 2017 20:44:34 模組2.py[line:62] ERROR error messageThu, 22 Jun 2017 20:44:34 模組2.py[line:63] CRITICAL critical message

logging中的相關參數:

logging.basicConfig()函數中可通過具體參數來更改logging模組預設行為,可用參數有:filename:用指定的檔案名稱建立FiledHandler,這樣日誌會被儲存在指定的檔案中。filemode:檔案開啟檔案,在指定了filename時使用這個參數,預設值為“a”還可指定為“w”。format:指定handler使用的日誌顯示格式。datefmt:指定日期時間格式。level:設定rootlogger(後邊會講解具體概念)的記錄層級stream:用指定的stream建立StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者檔案(f=open(‘test.log’,’w’)),預設為sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。format參數中可能用到的格式化串:%(name)s Logger的名字%(levelno)s 數字形式的記錄層級%(levelname)s 文本形式的記錄層級%(pathname)s 調用日誌輸出函數的模組的完整路徑名,可能沒有%(filename)s 調用日誌輸出函數的模組的檔案名稱%(module)s 調用日誌輸出函數的模組名%(funcName)s 調用日誌輸出函數的函數名%(lineno)d 調用日誌輸出函數的語句所在的程式碼%(created)f 目前時間,用UNIX標準的表示時間的浮 點數表示%(relativeCreated)d 輸出日誌資訊時的,自Logger建立以 來的毫秒數%(asctime)s 字串形式的目前時間。預設格式是 “2003-07-08 16:49:45,896”。逗號後面的是毫秒%(thread)d 線程ID。可能沒有%(threadName)s 線程名。可能沒有%(process)d 進程ID。可能沒有%(message)s使用者輸出的訊息

 logger:另一種日誌配置方式。

import logginglogger = logging.getLogger()# 建立一個handler,用於寫入記錄檔fh = logging.FileHandler(‘test.log‘)# 再建立一個handler,用於輸出到控制台ch = logging.StreamHandler()formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)fh.setFormatter(formatter)ch.setFormatter(formatter)logger.addHandler(fh) #logger對象可以添加多個fh和ch對象logger.addHandler(ch)logger.debug(‘logger debug message‘)logger.info(‘logger info message‘)logger.warning(‘logger warning message‘)logger.error(‘logger error message‘)logger.critical(‘logger critical message‘)

json:

  序列化?

    我們把對象從記憶體中變成可儲存或傳輸的過程稱之為序列化。反過來把變數內容從序列化的對象重新讀到記憶體裡稱之為還原序列化,即unpickling。

    各種程式設計語言之間可能參數啊,資料格式啊都不一樣,這時如果在這些程式設計語言之間傳遞資料,就需要把對象序列化為標準格式。

 json和Python的資料類型對應表:

序列化:

import jsondic={‘name‘:‘alvin‘,‘age‘:23,‘sex‘:‘male‘}print(type(dic))data=json.dumps(dic)     #使用 json.dumps()進行序列化print("type",type(data))print("data",data)執行結果:D:\Python\Python36-32\python.exe E:/Python/DAY-13/模組2.py<class ‘dict‘>type <class ‘str‘>data {"name": "alvin", "age": 23, "sex": "male"}Process finished with exit code 0

序列化&還原序列化樣本:

import jsondic={‘name‘:‘alvin‘,‘age‘:23,‘sex‘:‘male‘}data=json.dumps(dic)   #序列化字典with open(‘test.json‘,‘w‘) as f:    f.write(data)  #儲存結果到檔案中with open(‘test.json‘,‘r‘) as f:       data = json.load(f) #從檔案中擷取資料,還原序列化    print(data,type(data))  #列印結果,類型(根據結果來看,資料類型成功還原)執行結果:D:\Python\Python36-32\python.exe E:/Python/DAY-13/模組2.py{‘name‘: ‘alvin‘, ‘age‘: 23, ‘sex‘: ‘male‘} <class ‘dict‘>Process finished with exit code 0

另一種序列化和還原序列化樣本:

f=open(‘序列化對象‘,‘w‘)f.write(data)  #-------------------等價於json.dump(dic,f)f.close()#-----------------------------還原序列化<br>import jsonf=open(‘序列化對象‘)new_data=json.loads(f.read())#  等價於data=json.load(f)print(type(new_data))

pickle:不同於json這是在Python程式之間使用的。使用基本和json是相同的。

##----------------------------序列化import pickle dic={‘name‘:‘alvin‘,‘age‘:23,‘sex‘:‘male‘} print(type(dic))#<class ‘dict‘> j=pickle.dumps(dic)print(type(j))#<class ‘bytes‘>  f=open(‘序列化對象_pickle‘,‘wb‘)#注意是w是寫入str,wb是寫入bytes,j是‘bytes‘f.write(j)  #-------------------等價於pickle.dump(dic,f) f.close()#-------------------------還原序列化import picklef=open(‘序列化對象_pickle‘,‘rb‘) data=pickle.loads(f.read())#  等價於data=pickle.load(f) print(data[‘age‘])

python基礎之模組part2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.