python之旅六【第六篇】模块
json和pickle
用于序列化的兩個模塊
json,用于字符串 和 python數據類型間進行轉換
pickle,用于python特有的類型 和 python的數據類型間進行轉換
json模塊提供了四個功能:dumps、dump、loads、load
pickle模塊提供了四個功能:dumps、dump、loads、load
json dumps把數據類型轉換成字符串 dump把數據類型轉換成字符串并存儲在文件中? loads把字符串轉換成數據類型? load把文件打開從字符串轉換成數據類型
pickle同理
現在有個場景在不同設備之間進行數據交換很low的方式就是傳文件,dumps可以直接把服務器A中內存的東西發給其他服務器,比如B服務器、 在很多場景下如果用pickle的話那A的和B的程序都的是python程序這個是不現實的,很多時候都是不同的程序之間的內存交換怎么辦?就用到了json(和html類似的語言) 并且josn能dump的結果更可讀,那么有人就問了,那還用pickle做什么不直接用josn,是這樣的josn只能把常用的數據類型序列化(列表、字典、列表、字符串、數字、),比如日期格式、類對象!josn就不行了。 為什么他不能序列化上面的東西呢?因為josn是跨語言的! 具體實例如下 1 import json 2 ''' 3 json dumps把數據類型轉換成字符串 dump把數據類型轉換成字符串并存儲在文件中 4 loads把字符串轉換成數據類型 load把文件打開從字符串轉換成數據類型 5 ''' 6 name = {'name':'dicky','age':19} 7 print type(json.dumps(name)) #數據類型轉換成字符串 8 print json.dumps(name) 9 print json.loads(json.dumps(name)) 10 print type(json.loads(json.dumps(name))) #字符串轉換成字典 11 12 結果 13 <type 'str'> 14 {"age": 19, "name": "dicky"} 15 {u'age': 19, u'name': u'dicky'} 16 <type 'dict'> 1 ''' 2 dump把數據類型轉換成字符串并存儲在文件中 3 load把文件打開從字符串轉換成數據類型 4 ''' 5 new_list = {'age':19,'work':'IT'} 6 with open ('test1','w') as openfile: 7 json.dump(new_list,openfile) 8 print "以上就是dump......." 9 10 with open('test1','rb') as readfile: 11 result=json.load(readfile) 12 print "load完成",type(result) 13 print result 14 15 16 結果 17 以上就是dump....... 18 load完成 <type 'dict'> 19 {u'age': 19, u'work': u'IT'}?ConfigParser
用于對特定的配置進行操作,當前模塊的名稱在 python 3.x 版本中變更為 configparser。
1 import ConfigParser 2 3 ''' 4 test1 5 [section1] 6 name = dicky 7 k2 = v2 8 age = 13 9 10 [section2] 11 k1 = v1 12 work=IT 13 [shuaige] 14 name = dicky 15 ''' 16 config=ConfigParser.ConfigParser() 17 config.read('test1') 18 #讀取 19 sec=config.sections() 20 print sec 21 option=config.options('section1') 22 print option 23 item=config.items('section1') 24 print item 25 val = config.get('section1','name') 26 print val 27 val1 = config.getint('section1','age') 28 print val1 29 #修改 30 sec1=config.remove_section('section3') #刪除色彩tion3 31 config.write(open('test1','w')) 32 # sec = config.add_section('shuaige') 33 # config.write(open('test1','w')) 34 # 35 # config.set('shuaige','name','dicky') 36 # config.write(open('test1','w')) 37 38 config.remove_option('section2','work') 39 config.write(open('test1','w')) 40 41 結果 42 ['section1', 'section2', 'shuaige'] 43 ['name', 'k2', 'age'] 44 [('name', 'dicky'), ('k2', 'v2'), ('age', '13')] 45 dicky 46 13?操作系統相關命令
os.system() #執行系統命令
其他的都廢棄掉了,以后使用subprocess代替了
主要介紹subprocess
call
1 subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) 2 執行命令,返回狀態碼 3 ret = subprocess.call(["ls", "-l"], shell=False) 4 ret = subprocess.call("ls -l", shell=True) 5 shell = True ,允許 shell 命令是字符串形式,也就是使用shell來執行,一般情況下,我們要使用shell=False,也是默認的一種形式,模式就是shell=Falsecheck_call
1 subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) 2 執行命令,如果執行狀態碼是 0 ,則返回0,否則拋異常 3 subprocess.check_call(["ls", "-l"]) 4 subprocess.check_call("exit 1", shell=True)check_output
1 subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) 2 執行命令,如果狀態碼是 0 ,則返回執行結果,否則拋異常 3 subprocess.check_output(["echo", "Hello World!"]) 4 subprocess.check_output("exit 1", shell=True) 5 捕獲異常 6 若要在結果中捕獲標準錯誤,可以使用 stderr=subprocess.STDOUT 7 >>> subprocess.check_output( 8 ... "ls non_existent_file; exit 0", 9 ... stderr=subprocess.STDOUT, 10 ... shell=True) 11 'ls: non_existent_file: No such file or directory\n'Popen
1 class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0) 2 參數 3 args:shell命令,可以是字符串或者序列類型(如:list,元組)最好傳入序列 4 bufsize:指定緩沖。0 無緩沖,1 行緩沖,其他 緩沖區大小,負值 系統緩沖 5 stdin, stdout, stderr:分別表示程序的標準輸入、輸出、錯誤句柄 6 preexec_fn:只在Unix平臺下有效,用于指定一個可執行對象(callable object),它將在子進程運行之前被調用 7 close_sfs:在windows平臺下,如果close_fds被設置為True,則新創建的子進程將不會繼承父進程的輸入、輸出、錯誤管道。 8 所以不能將close_fds設置為True同時重定向子進程的標準輸入、輸出與錯誤(stdin, stdout, stderr)。 9 shell:同上 10 cwd:用于設置子進程的當前目錄 11 env:用于指定子進程的環境變量。如果env = None,子進程的環境變量將從父進程中繼承。 12 universal_newlines:不同系統的換行符不同,True -> 同意使用 \n 13 startupinfo與createionflags只在windows下有效 14 將被傳遞給底層的CreateProcess()函數,用于設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等?args
如果args?是一個字符串,該字符串將解釋為要執行的程序的名字或路徑。然而,這只能在不傳遞參數給程序時可行。
如下解決
1 前提是創建好文件egg.txt 2 >>> import shlex, subprocess 3 >>> command_line = raw_input() 4 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" 5 >>> args = shlex.split(command_line) 6 >>> print args 7 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] 8 >>> p = subprocess.Popen(args) # Success!簡單執行命令
1 ret1 = subprocess.Popen(["mkdir","t1"]) 2 ret2 = subprocess.Popen("mkdir t2", shell=True)Popen?類的實例具有以下方法
1 Popen.poll() 檢查子進程是否已經終止 2 Popen.wait() 等待子進程終止 3 Popen.communicate(input=None) 4 與進程交互:將數據發送到標準輸入。從標準輸出和標準錯誤讀取數據,直至到達文件末尾。等待進程終止。可選的input 參數應該是一個要發送給子進程的字符串,如果沒有數據要發送給子進程則應該為None。 5 注意如果你需要發送數據到進程的標準輸入,你需要以stdin=PIPE創建Popen對象。類似地,在結果的元組中若要得到非None的數據,你還需要給出stdout=PIPE和/或stderr=PIPE。 6 Popen.send_signal(signal) 發送信號signal 給子進程。 7 Popen.terminate() 終止子進程。 8 Popen.kill() 殺死子進程。 9 Popen.stdin 如果stdin 參數為PIPE,則該屬性為一個文件對象,它提供子進程的輸入。否則,為None。 10 Popen.stdout 如果stdout 參數為PIPE,則該屬性是一個文件對象,它提供子進程中的輸出。否則,為None。 11 Popen.stderr 如果stderr 參數為PIPE,則該屬性是一個文件對象,它提供子進程中的錯誤輸出。否則,為None。 12 Popen.pid 子進程的進程ID。 13 注意如果你設置shell 參數為True,那么它是產生的shell的進程ID。 View Code?依賴,進入某環境輸入
import subprocessobj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)保存輸出
1 import subprocess 2 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 4 out_error_list = obj.communicate('print "hello"') 5 print out_error_list 6 7 import subprocess 8 9 obj = subprocess.Popen(["ls"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 10 out_error_list = obj.communicate() 11 print out_error_list另外一種
stdout.read()
1 import subprocess 2 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 4 obj.stdin.write('print 1 \n ') 5 obj.stdin.write('print 2 \n ') 6 obj.stdin.write('print 3 \n ') 7 obj.stdin.write('print 4 \n ') 8 obj.stdin.close() 9 10 cmd_out = obj.stdout.read() 11 obj.stdout.close() 12 cmd_error = obj.stderr.read() 13 obj.stderr.close() 14 15 print cmd_out 16 print cmd_error加密模塊
?md5已經廢棄
1 import md5 2 hash = md5.new() 3 hash.update('admin') 4 print hash.hexdigest() View Codesha廢棄
1 import sha 2 hash = sha.new() 3 hash.update('admin') 4 print hash.hexdigest() View Code?hashlib替代了以上的加密
1 import hashlib 2 hash = hashlib.md5() 3 hash.update('admin') 4 print hash.hexdigest() 1 sha加密 2 hash = hashlib.sha1() 3 hash.update('admin') 4 print hash.hexdigest()其他的一樣,就不一一列舉了
?
以上加密算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對加密算法中添加自定義key再來做加密。
import hashlib# ######## md5 ########hash = hashlib.md5('898oaFs09f') #自定義的key hash.update('admin') print hash.hexdigest()還不夠吊?python 還有一個 hmac 模塊,它內部對我們創建 key 和 內容 再進行處理然后再加密
1 import hmac 2 h = hmac.new('wueiqi') 3 h.update('hellowo') 4 print h.hexdigest()?日志模塊logging
?簡單用法
1 import logging 2 3 logging.basicConfig(filename='log.log', 4 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', 5 datefmt='%Y-%m-%d %H:%M:%S %p', 6 level=10) 7 8 logging.debug('debug') 9 logging.info('info') 10 logging.warning('warning') 11 logging.error('error') 12 logging.critical('critical') 13 logging.log(10,'log') 14 15 級別 16 CRITICAL = 50 17 FATAL = CRITICAL 18 ERROR = 40 19 WARNING = 30 20 WARN = WARNING 21 INFO = 20 22 DEBUG = 10 23 NOTSET = 0?詳細參考鏈接:http://www.jianshu.com/p/feb86c06c4f4
?
?
?
?
?
?
?
?
?
轉載于:https://www.cnblogs.com/Dicky-Zhang/p/7406736.html
總結
以上是生活随笔為你收集整理的python之旅六【第六篇】模块的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: R语言学习
- 下一篇: 【Redis扩展篇(一)】过期策略
