1. 程式人生 > >重新學習python系列(四)? WTF?

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

== 字符 計數器 函數 有用 read counter pri random

多進程:

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

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

# multiprocessing.py
import os

print ‘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, Queue
import 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.‘ % value

if __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-8
import 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().name

print ‘thread %s is running...‘ % threading.current_thread().name
t = 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-8
from collections import defaultdict
dd = defaultdict(lambda: ‘N/A‘)
dd[‘a‘] = 123
print 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 base64
text = ‘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?