重新學習python系列(四)? WTF?

來源:互聯網
上載者:User

標籤:div   寫入   counter   封裝   迴圈   queue   fifo   key   and   

多進程:

fork()調用一次,返回兩次,因為作業系統自動把當前進程(稱為父進程)複製了一份(稱為子進程),

然後,分別在父進程和子進程內返回
getppid()得到父進程的ID
getpid() 得到當前進程的ID

# multiprocessing.pyimport osprint ‘Process (%s) start...‘ % os.getpid()pid = os.fork()if pid==0:    print ‘I am child process (%s) and my parent is %s.‘ % (os.getpid(), os.getppid())else:    print ‘I (%s) just created a child process (%s).‘ % (os.getpid(), pid)Process (876) start...I (876) just created a child process (877).I am child process (877) and my parent is 876.

 

 

進程之間的通訊:

from multiprocessing import Process, Queueimport os, time, random# 寫資料進程執行的代碼:def write(q):    for value in [‘A‘, ‘B‘, ‘C‘]:        print ‘Put %s to queue...‘ % value        q.put(value)        time.sleep(random.random())# 讀資料進程執行的代碼:def read(q):    while True:        value = q.get(True)        print ‘Get %s from queue.‘ % valueif __name__==‘__main__‘:    # 父進程建立Queue,並傳給各個子進程:    q = Queue()    pw = Process(target=write, args=(q,))    pr = Process(target=read, args=(q,))    # 啟動子進程pw,寫入:    pw.start()    # 啟動子進程pr,讀取:    pr.start()    # 等待pw結束:    pw.join()    # pr進程裡是死迴圈,無法等待其結束,只能強行終止:    pr.terminate()

 

 

多線程:

Python的標準庫提供了兩個模組:threadthreadingthread是低級模組,threading是進階模組,對thread進行了封裝。

絕大多數情況下,我們只需要使用threading這個進階模組。

啟動一個線程就是把一個函數傳入並建立Thread執行個體,然後調用start()開始執行:

#coding=utf-8import time, threading# 新線程執行的代碼:def loop():    print ‘thread %s is running...‘ % threading.current_thread().name    n = 0    while n < 5:        n = n + 1        print ‘thread %s >>> %s‘ % (threading.current_thread().name, n)        time.sleep(1)    print ‘thread %s ended.‘ % threading.current_thread().nameprint ‘thread %s is running...‘ % threading.current_thread().namet = threading.Thread(target=loop, name=‘LoopThread‘)t.start()t.join()print ‘thread %s ended.‘ % threading.current_thread().name

 。。。。。。。

 

 

collections模組提供了一些有用的集合類,可以根據需要選用。

defaultdict

使用dict時,如果引用的Key不存在,就會拋出KeyError。如果希望key不存在時,返回一個預設值,就可以用defaultdict

#coding=utf-8from collections import defaultdictdd = defaultdict(lambda: ‘N/A‘)dd[‘a‘] = 123print dd[‘a‘]print dd[‘b‘]
OrderedDict

使用dict時,Key是無序的。在對dict做迭代時,我們無法確定Key的順序。

如果要保持Key的順序,可以用OrderedDict

OrderedDict可以實現一個FIFO(先進先出)的dict,當容量超出限制時,先刪除最早添加的Key:

。。。。。。。。。。。。。。

 

base64

>>> base64.b64encode(‘i\xb7\x1d\xfb\xef\xff‘)‘abcd++//‘>>> base64.urlsafe_b64encode(‘i\xb7\x1d\xfb\xef\xff‘)‘abcd--__‘>>> base64.urlsafe_b64decode(‘abcd--__‘)‘i\xb7\x1d\xfb\xef\xff‘

 

python計數器Count 

# -*- coding:utf-8 -*-"""  python計數器Counter  需匯入模組collections"""import collections # 統計各個字元出現的次數,以字典形式返回obj = collections.Counter(‘adfsdfsdfswrwerwegfhgfhgh‘)print obj# elements => 原生的傳入的值(‘adfsdfsdfswrwerwegfhgfhgh‘)for v in obj.elements():    print v # 按參數給定的個數返回print obj.most_common(4)

 # 執行結果顯示 Counter({‘f‘: 5, ‘d‘: 3, ‘g‘: 3, ‘h‘: 3, ‘s‘: 3, ‘w‘: 3, ‘e‘: 2, ‘r‘: 2, ‘a‘: 1}) [(‘f‘, 5), (‘d‘, 3), (‘g‘, 3), (‘h‘, 3)]

 

 

請寫一個能處理 去掉=的base64解碼函數:

import base64text = ‘YWJjZA‘if not len(text)%4==0:    print base64.b64decode(text+"="*(len(text)%4))

 

structpack函數把任意資料類型變成字串:

>>> import struct>>> struct.pack(‘>I‘, 10240099)‘\x00\[email protected]‘

 unpackstr變成相應的資料類型:

>>> struct.unpack(‘>IH‘, ‘\xf0\xf0\xf0\xf0\x80\x80‘)(4042322160, 32896)

 

重新學習python系列(四)? WTF?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.