Python之經常使用模塊(待更新)

模塊,用一砣代碼實現了某個功能的代碼集合。 html

相似於函數式編程和麪向過程編程,函數式編程則完成一個功能,其餘代碼用來調用便可,提供了代碼的重用性和代碼間的耦合。而對於一個複雜的功能來,可能須要多個函數才能完成(函數又能夠在不一樣的.py文件中),n個 .py 文件組成的代碼集合就稱爲模塊。node

如:os 是系統相關的模塊;file是文件操做相關的模塊python

模塊分爲三種:git

  • 自定義模塊
  • 內置模塊
  • 開源模塊

 

自定義模塊

 

一、定義模塊程序員

情景一:github

  

情景二:web

  

情景三:算法

  

二、導入模塊shell

Python之因此應用愈來愈普遍,在必定程度上也依賴於其爲程序員提供了大量的模塊以供使用,若是想要使用模塊,則須要導入。導入模塊有一下幾種方法:編程

1
2
3
4
import  module
from  module.xx.xx  import  xx
from  module.xx.xx  import  xx as rename 
from  module.xx.xx  import  *

導入模塊其實就是告訴Python解釋器去解釋那個py文件

  • 導入一個py文件,解釋器解釋該py文件
  • 導入一個包,解釋器解釋該包下的 __init__.py 文件

 

開源模塊

 

1、下載安裝

下載安裝有兩種方式:

yum 
pip
apt-get
...
下載源碼
解壓源碼
進入目錄
編譯源碼    python setup.py build
安裝源碼    python setup.py install
注:在使用源碼安裝時,須要使用到gcc編譯和python開發環境,因此,須要先執行:
1
2
3
4
yum install gcc
yum install python - devel
apt - get python - dev

安裝成功後,模塊會自動安裝到 sys.path 中的某個目錄中,如:

1
/ usr / lib / python2. 7 / site - packages /

2、導入模塊

同自定義模塊中導入的方式

3、模塊 paramiko

paramiko是一個用於作遠程控制的模塊,使用該模塊能夠對遠程服務器進行命令或文件操做,值得一說的是,fabric和ansible內部的遠程管理就是使用的paramiko來現實。

一、下載安裝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# pycrypto,因爲 paramiko 模塊內部依賴pycrypto,因此先下載安裝pycrypto
  
# 下載安裝 pycrypto
wget http: / / files.cnblogs.com / files / wupeiqi / pycrypto - 2.6 . 1.tar .gz
tar  - xvf pycrypto - 2.6 . 1.tar .gz
cd pycrypto - 2.6 . 1
python setup.py build
python setup.py install
  
# 進入python環境,導入Crypto檢查是否安裝成功
  
# 下載安裝 paramiko
wget http: / / files.cnblogs.com / files / wupeiqi / paramiko - 1.10 . 1.tar .gz
tar  - xvf paramiko - 1.10 . 1.tar .gz
cd paramiko - 1.10 . 1
python setup.py build
python setup.py install
  
# 進入python環境,導入paramiko檢查是否安裝成功

二、使用模塊

複製代碼
#!/usr/bin/env python
#coding:utf-8

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.108', 22, 'alex', '123')
stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close();
複製代碼
複製代碼
import paramiko

private_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(private_key_path)

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('主機名 ', 端口, '用戶名', key)

stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
ssh.close()
複製代碼
複製代碼
import os,sys
import paramiko

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='123')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test.py','/tmp/test.py') 
t.close()


import os,sys
import paramiko

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',password='123')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test.py','/tmp/test2.py')
t.close()
複製代碼
複製代碼
import paramiko

pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path)

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',pkey=key)

sftp = paramiko.SFTPClient.from_transport(t)
sftp.put('/tmp/test3.py','/tmp/test3.py') 

t.close()

import paramiko

pravie_key_path = '/home/auto/.ssh/id_rsa'
key = paramiko.RSAKey.from_private_key_file(pravie_key_path)

t = paramiko.Transport(('182.92.219.86',22))
t.connect(username='wupeiqi',pkey=key)

sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/tmp/test3.py','/tmp/test4.py') 

t.close()
複製代碼

 

內置模塊

 

time & datetime模塊

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import  time
import  datetime
 
time
print (time.clock())   #返回處理器時間,3.3之後廢棄 4.444098792316153e-07
print (time.process_time())  #返回處理器時間 0.031200199999999997
print (time.time())      #返回當前系統時間戳 1463472071.3892002
print (time.ctime())     #返回當前系統時間 Tue May 17 16:01:11 2016
print (time.ctime(time.time() - 86400 ))    #轉換成字符串格式 Mon May 16 16:01:11 2016
print (time.gmtime(time.time() - 86400 ))   #將時間戳轉換成struct_time格式 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=16, tm_hour=8, tm_min=1, tm_sec=11, tm_wday=0, tm_yday=137, tm_isdst=0)
print (time.localtime(time.time() - 86400 ))   #將時間戳轉換成struct_time格式,本地時間。 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=16, tm_hour=16, tm_min=13, tm_sec=25, tm_wday=0, tm_yday=137, tm_isdst=0)
print (time.mktime(time.localtime()))   #與time.localtime()功能相反,將struct_time格式轉回成時間戳格式  1463472904.0
time.sleep( 4 #sleep 每隔四秒以執行
print (time.strftime( "%Y-%m-%d %H:%M:%S" ,time.gmtime()) )  #將struct_time格式轉成指定的字符串格式  2016-05-17 08:16:22
 
datetime
print (datetime.date.today())  #輸出格式 2016-05-17
print (datetime.date.fromtimestamp(time.time() - 86400 ) )  # 將時間戳轉成日期格式 2016-05-16
current_time  =  datetime.datetime.now()  #
print (current_time)  #輸出2016-05-17 16:17:59.863200
print (current_time.timetuple())  #返回struct_time格式  time.struct_time(tm_year=2016, tm_mon=5, tm_mday=17, tm_hour=16, tm_min=17, tm_sec=59, tm_wday=1, tm_yday=138, tm_isdst=-1)
 
#datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
print (current_time.replace( 2016 , 5 , 17 ))  #輸出2016-05-17 16:19:33.753200,返回當前時間,但指定的值將被替換
 
str_to_date  =  datetime.datetime.strptime( "21/11/06 16:30" "%d/%m/%y %H:%M" #將字符串轉換成日期格式
new_date1  =  datetime.datetime.now()  +  datetime.timedelta(days = 10 #比如今加10天 2016-05-27 16:21:16.279200
new_date2  =  datetime.datetime.now()  +  datetime.timedelta(days = - 10 #比如今減10天 2016-05-07 16:21:44.459200
new_date3  =  datetime.datetime.now()  +  datetime.timedelta(hours = - 10 #比如今減10小時 2016-05-17 06:22:01.299200
new_date4  =  datetime.datetime.now()  +  datetime.timedelta(seconds = 120 #比如今+120s 2016-05-17 16:24:10.917200
new_date5  =  datetime.datetime.now()  +  datetime.timedelta(weeks = 20 #比如今+10周 2016-10-04 16:23:02.904200
print (new_date5)
Directive Meaning Notes
%a Locale’s abbreviated weekday name.  
%A Locale’s full weekday name.  
%b Locale’s abbreviated month name.  
%B Locale’s full month name.  
%c Locale’s appropriate date and time representation.  
%d Day of the month as a decimal number [01,31].  
%H Hour (24-hour clock) as a decimal number [00,23].  
%I Hour (12-hour clock) as a decimal number [01,12].  
%j Day of the year as a decimal number [001,366].  
%m Month as a decimal number [01,12].  
%M Minute as a decimal number [00,59].  
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
%w Weekday as a decimal number [0(Sunday),6].  
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
%x Locale’s appropriate date representation.  
%X Locale’s appropriate time representation.  
%y Year without century as a decimal number [00,99].  
%Y Year with century as a decimal number.  
%z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z Time zone name (no characters if no time zone exists).  
%% A literal '%' character.

 

random模塊

隨機數

1
2
3
4
mport random
print  random.random()
print  random.randint( 1 , 2 )
print  random.randrange( 1 , 10 )

生成隨機驗證碼

1
2
3
4
5
6
7
8
9
10
11
import   random
tmp  =  ""
for  in  range ( 6 ):
     rad1  =  random.randrange( 4 )
     if  rad1  = = 1  or  rad1  = = 3 :
         rad2  =  random.randrange( 0 , 9 )
         tmp  + =  str (rad2)
     else :
         rad3  =  random.randrange( 65 , 90 )
         tmp  + =  chr (rad3)
print (tmp)

sys模塊

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import  sys
import  time
print (sys.argv)     #['C:/Users/Administrator/PycharmProjects/zyl/day-6/datetime,time模塊/SYS.PY.py']
 
print (sys.path)     #返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
 
print (exit())    #退出程序,正常退出時exit(0)
 
print (sys.version)   #3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
 
print (sys.maxsize)    #9223372036854775807  最大的Int值
 
print (sys.platform)   #win32       操做系統類型
 
 
####################################安裝包流程不換行顯示##################################
for   in  range ( 31 ):
     sys.stdout.write( "\r" )          #清空當前數據網上疊加
     sys.stdout.write( "%s%% | %s "  % ( int (i / 30 * 100 ), int (i / 30 * 100 ) * "#" ))
     sys.stdout.flush()
     time.sleep( 0.3 )
 
####################################安裝流程換行顯示####################################
 
for  in  range ( 101 ):
     sys.stdout.write( "\r" )
     sys.stdout.write( "%s%% | %s \n"  % (i,i * "#" ))
     sys.stdout.flush()
     time.sleep( 0.1 )

 

json & pickle 模塊

用於序列化的兩個模塊

  • json,用於字符串 和 python數據類型間進行轉換
  • pickle,用於python特有的類型 和 python的數據類型間進行轉換

Json模塊提供了四個功能:dumps、dump、loads、load

pickle模塊提供了四個功能:dumps、dump、loads、load

複製代碼
import pickle

accounts = {
    1000: {
        'name':'Zhangyanlin',
        'email': '75501664@126.com',
        'passwd': 'abc123',
        'balance': 15000,
        'phone': 13651054608,
        'bank_acc':{
            'ICBC':14324234,
            'CBC' : 235234,
            'ABC' : 35235423
        }
    },
    1001: {
        'name': 'CaiXin Guo',
        'email': 'caixin@126.com',
        'passwd': 'abc145323',
        'balance': -15000,
        'phone': 1345635345,
        'bank_acc': {
            'ICBC': 4334343,
        }
    },
}

################################原始寫入文件中去###############################
with open("zhang","wb") as f:
    f.write(pickle.dumps(accounts))               #打開文件將原數據保存到文件中


################################購物環節#######################################
with open("zhang","rb") as f:
   zhang_dic = pickle.loads(f.read())             #讀取出文件裏的內容賦值給zhang_dic變量

zhang_dic[1000]['balance'] -= 1000              #購物消費100,總價減去1000塊錢


with open("zhang","wb") as f:
    f.write(pickle.dumps(zhang_dic))              #寫入到數據中去

##############################刷新購物後文件裏面的數據#########################

with open("zhang","rb") as f:
    shop_old = pickle.loads(f.read())          #把新數據更新到文件中去
print(shop_old)
複製代碼

 

複製代碼
#json.loads(參數)將字符串轉換成python識別的字符
li = '[11,22,33,44,55,66,77,88,99]'
dic = '{"sdkf":"123","askd":"123"}'
print(json.loads(li),type(json.loads(li)))    #列表類型
print(json.loads(dic),type(json.loads(dic)))  #字典類型

#json.dumps(參數)將python字符轉換成其餘語言識別的字符
li = [11,22,33,44,55]
dic = {"sdkf":"123","askd":"123"}
print(json.dumps(li),type(json.dumps(li)))        #轉成字符串
print(json.dumps(dic),type(json.dumps(dic)))      #轉成字符串
複製代碼

 

 

collection系列

一、計數器(counter)

Counter是對字典類型的補充,用於追蹤值的出現次數。

ps:具有字典的全部功能 + 本身的功能

1
2
3
=  Counter( 'abcdeabcdabcaba' )
print  c
輸出:Counter({ 'a' 5 'b' 4 'c' 3 'd' 2 'e' 1 })
複製代碼
########################################################################
###  Counter
########################################################################

class Counter(dict):
    '''Dict subclass for counting hashable items.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

    >>> c = Counter('abcdeabcdabcaba')  # count elements from a string

    >>> c.most_common(3)                # three most common elements
    [('a', 5), ('b', 4), ('c', 3)]
    >>> sorted(c)                       # list all unique elements
    ['a', 'b', 'c', 'd', 'e']
    >>> ''.join(sorted(c.elements()))   # list elements with repetitions
    'aaaaabbbbcccdde'
    >>> sum(c.values())                 # total of all counts

    >>> c['a']                          # count of letter 'a'
    >>> for elem in 'shazam':           # update counts from an iterable
    ...     c[elem] += 1                # by adding 1 to each element's count
    >>> c['a']                          # now there are seven 'a'
    >>> del c['b']                      # remove all 'b'
    >>> c['b']                          # now there are zero 'b'

    >>> d = Counter('simsalabim')       # make another counter
    >>> c.update(d)                     # add in the second counter
    >>> c['a']                          # now there are nine 'a'

    >>> c.clear()                       # empty the counter
    >>> c
    Counter()

    Note:  If a count is set to zero or reduced to zero, it will remain
    in the counter until the entry is deleted or the counter is cleared:

    >>> c = Counter('aaabbc')
    >>> c['b'] -= 2                     # reduce the count of 'b' by two
    >>> c.most_common()                 # 'b' is still in, but its count is zero
    [('a', 3), ('c', 1), ('b', 0)]

    '''
    # References:
    #   http://en.wikipedia.org/wiki/Multiset
    #   http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
    #   http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
    #   http://code.activestate.com/recipes/259174/
    #   Knuth, TAOCP Vol. II section 4.6.3

    def __init__(self, iterable=None, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

        '''
        super(Counter, self).__init__()
        self.update(iterable, **kwds)

    def __missing__(self, key):
        """ 對於不存在的元素,返回計數器爲0 """
        'The count of elements not in the Counter is zero.'
        # Needed so that self[missing_item] does not raise KeyError
        return 0

    def most_common(self, n=None):
        """ 數量大於等n的全部元素和計數器 """
        '''List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        >>> Counter('abcdeabcdabcaba').most_common(3)
        [('a', 5), ('b', 4), ('c', 3)]

        '''
        # Emulate Bag.sortedByCount from Smalltalk
        if n is None:
            return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)
        return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))

    def elements(self):
        """ 計數器中的全部元素,注:此處非全部元素集合,而是包含全部元素集合的迭代器 """
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.iteritems()))

    # Override dict methods where necessary

    @classmethod
    def fromkeys(cls, iterable, v=None):
        # There is no equivalent method for counters because setting v=1
        # means that no element can have a count greater than one.
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

    def update(self, iterable=None, **kwds):
        """ 更新計數器,其實就是增長;若是原來沒有,則新建,若是有則加一 """
        '''Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch

        '''
        # The regular dict.update() operation makes no sense here because the
        # replace behavior results in the some of original untouched counts
        # being mixed-in with all of the other counts for a mismash that
        # doesn't have a straight-forward interpretation in most counting
        # contexts.  Instead, we implement straight-addition.  Both the inputs
        # and outputs are allowed to contain zero and negative counts.

        if iterable is not None:
            if isinstance(iterable, Mapping):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    super(Counter, self).update(iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwds:
            self.update(kwds)

    def subtract(self, iterable=None, **kwds):
        """ 相減,原來的計數器中的每個元素的數量減去後添加的元素的數量 """
        '''Like dict.update() but subtracts counts instead of replacing them.
        Counts can be reduced below zero.  Both the inputs and outputs are
        allowed to contain zero and negative counts.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.subtract('witch')             # subtract elements from another iterable
        >>> c.subtract(Counter('watch'))    # subtract elements from another counter
        >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
        >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
        -1

        '''
        if iterable is not None:
            self_get = self.get
            if isinstance(iterable, Mapping):
                for elem, count in iterable.items():
                    self[elem] = self_get(elem, 0) - count
            else:
                for elem in iterable:
                    self[elem] = self_get(elem, 0) - 1
        if kwds:
            self.subtract(kwds)

    def copy(self):
        """ 拷貝 """
        'Return a shallow copy.'
        return self.__class__(self)

    def __reduce__(self):
        """ 返回一個元組(類型,元組) """
        return self.__class__, (dict(self),)

    def __delitem__(self, elem):
        """ 刪除元素 """
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            super(Counter, self).__delitem__(elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # Multiset-style mathematical operations discussed in:
    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
    #       and at http://en.wikipedia.org/wiki/Multiset
    #
    # Outputs guaranteed to only include positive counts.
    #
    # To strip negative and zero counts, add-in an empty counter:
    #       c += Counter()

    def __add__(self, other):
        '''Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            newcount = count + other[elem]
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count > 0:
                result[elem] = count
        return result

    def __sub__(self, other):
        ''' Subtract count, but keep only results with positive counts.

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            newcount = count - other[elem]
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count < 0:
                result[elem] = 0 - count
        return result

    def __or__(self, other):
        '''Union is the maximum of value in either of the input counters.

        >>> Counter('abbb') | Counter('bcc')
        Counter({'b': 3, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            other_count = other[elem]
            newcount = other_count if count < other_count else count
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count > 0:
                result[elem] = count
        return result

    def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            other_count = other[elem]
            newcount = count if count < other_count else other_count
            if newcount > 0:
                result[elem] = newcount
        return result

Counter
複製代碼

 

二、有序字典(orderedDict )

orderdDict是對字典類型的補充,他記住了字典元素添加的順序

複製代碼
class OrderedDict(dict):
    'Dictionary that remembers insertion order'
    # An inherited dict maps keys to values.
    # The inherited dict provides __getitem__, __len__, __contains__, and get.
    # The remaining methods are order-aware.
    # Big-O running times for all methods are the same as regular dictionaries.

    # The internal self.__map dict maps keys to links in a doubly linked list.
    # The circular doubly linked list starts and ends with a sentinel element.
    # The sentinel element never gets deleted (this simplifies the algorithm).
    # Each link is stored as a list of length three:  [PREV, NEXT, KEY].

    def __init__(self, *args, **kwds):
        '''Initialize an ordered dictionary.  The signature is the same as
        regular dictionaries, but keyword arguments are not recommended because
        their insertion order is arbitrary.

        '''
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        try:
            self.__root
        except AttributeError:
            self.__root = root = []                     # sentinel node
            root[:] = [root, root, None]
            self.__map = {}
        self.__update(*args, **kwds)

    def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
        'od.__setitem__(i, y) <==> od[i]=y'
        # Setting a new item creates a new link at the end of the linked list,
        # and the inherited dictionary is updated with the new key/value pair.
        if key not in self:
            root = self.__root
            last = root[0]
            last[1] = root[0] = self.__map[key] = [last, root, key]
        return dict_setitem(self, key, value)

    def __delitem__(self, key, dict_delitem=dict.__delitem__):
        'od.__delitem__(y) <==> del od[y]'
        # Deleting an existing item uses self.__map to find the link which gets
        # removed by updating the links in the predecessor and successor nodes.
        dict_delitem(self, key)
        link_prev, link_next, _ = self.__map.pop(key)
        link_prev[1] = link_next                        # update link_prev[NEXT]
        link_next[0] = link_prev                        # update link_next[PREV]

    def __iter__(self):
        'od.__iter__() <==> iter(od)'
        # Traverse the linked list in order.
        root = self.__root
        curr = root[1]                                  # start at the first node
        while curr is not root:
            yield curr[2]                               # yield the curr[KEY]
            curr = curr[1]                              # move to next node

    def __reversed__(self):
        'od.__reversed__() <==> reversed(od)'
        # Traverse the linked list in reverse order.
        root = self.__root
        curr = root[0]                                  # start at the last node
        while curr is not root:
            yield curr[2]                               # yield the curr[KEY]
            curr = curr[0]                              # move to previous node

    def clear(self):
        'od.clear() -> None.  Remove all items from od.'
        root = self.__root
        root[:] = [root, root, None]
        self.__map.clear()
        dict.clear(self)

    # -- the following methods do not depend on the internal structure --

    def keys(self):
        'od.keys() -> list of keys in od'
        return list(self)

    def values(self):
        'od.values() -> list of values in od'
        return [self[key] for key in self]

    def items(self):
        'od.items() -> list of (key, value) pairs in od'
        return [(key, self[key]) for key in self]

    def iterkeys(self):
        'od.iterkeys() -> an iterator over the keys in od'
        return iter(self)

    def itervalues(self):
        'od.itervalues -> an iterator over the values in od'
        for k in self:
            yield self[k]

    def iteritems(self):
        'od.iteritems -> an iterator over the (key, value) pairs in od'
        for k in self:
            yield (k, self[k])

    update = MutableMapping.update

    __update = update # let subclasses override update without breaking __init__

    __marker = object()

    def pop(self, key, default=__marker):
        '''od.pop(k[,d]) -> v, remove specified key and return the corresponding
        value.  If key is not found, d is returned if given, otherwise KeyError
        is raised.

        '''
        if key in self:
            result = self[key]
            del self[key]
            return result
        if default is self.__marker:
            raise KeyError(key)
        return default

    def setdefault(self, key, default=None):
        'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
        if key in self:
            return self[key]
        self[key] = default
        return default

    def popitem(self, last=True):
        '''od.popitem() -> (k, v), return and remove a (key, value) pair.
        Pairs are returned in LIFO order if last is true or FIFO order if false.

        '''
        if not self:
            raise KeyError('dictionary is empty')
        key = next(reversed(self) if last else iter(self))
        value = self.pop(key)
        return key, value

    def __repr__(self, _repr_running={}):
        'od.__repr__() <==> repr(od)'
        call_key = id(self), _get_ident()
        if call_key in _repr_running:
            return '...'
        _repr_running[call_key] = 1
        try:
            if not self:
                return '%s()' % (self.__class__.__name__,)
            return '%s(%r)' % (self.__class__.__name__, self.items())
        finally:
            del _repr_running[call_key]

    def __reduce__(self):
        'Return state information for pickling'
        items = [[k, self[k]] for k in self]
        inst_dict = vars(self).copy()
        for k in vars(OrderedDict()):
            inst_dict.pop(k, None)
        if inst_dict:
            return (self.__class__, (items,), inst_dict)
        return self.__class__, (items,)

    def copy(self):
        'od.copy() -> a shallow copy of od'
        return self.__class__(self)

    @classmethod
    def fromkeys(cls, iterable, value=None):
        '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
        If not specified, the value defaults to None.

        '''
        self = cls()
        for key in iterable:
            self[key] = value
        return self

    def __eq__(self, other):
        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
        while comparison to a regular mapping is order-insensitive.

        '''
        if isinstance(other, OrderedDict):
            return dict.__eq__(self, other) and all(_imap(_eq, self, other))
        return dict.__eq__(self, other)

    def __ne__(self, other):
        'od.__ne__(y) <==> od!=y'
        return not self == other

    # -- the following methods support python 3.x style dictionary views --

    def viewkeys(self):
        "od.viewkeys() -> a set-like object providing a view on od's keys"
        return KeysView(self)

    def viewvalues(self):
        "od.viewvalues() -> an object providing a view on od's values"
        return ValuesView(self)

    def viewitems(self):
        "od.viewitems() -> a set-like object providing a view on od's items"
        return ItemsView(self)
複製代碼

 

三、默認字典(defaultdict) 

學前需求:

1
2
有以下值集合 [ 11 , 22 , 33 , 44 , 55 , 66 , 77 , 88 , 99 , 90. ..],將全部大於  66  的值保存至字典的第一個key中,將小於  66  的值保存至第二個key的值中。
即: { 'k1' : 大於 66  'k2' : 小於 66 }
複製代碼
values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = {}

for value in  values:
    if value>66:
        if my_dict.has_key('k1'):
            my_dict['k1'].append(value)
        else:
            my_dict['k1'] = [value]
    else:
        if my_dict.has_key('k2'):
            my_dict['k2'].append(value)
        else:
            my_dict['k2'] = [value]
複製代碼
複製代碼
from collections import defaultdict

values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = defaultdict(list)

for value in  values:
    if value>66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)
複製代碼

defaultdict是對字典的類型的補充,他默認給字典的值設置了一個類型。

複製代碼
class defaultdict(dict):
    """
    defaultdict(default_factory[, ...]) --> dict with default factory
    
    The default factory is called without arguments to produce
    a new value when a key is not present, in __getitem__ only.
    A defaultdict compares equal to a dict with the same items.
    All remaining arguments are treated the same as if they were
    passed to the dict constructor, including keyword arguments.
    """
    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D. """
        pass

    def __copy__(self, *args, **kwargs): # real signature unknown
        """ D.copy() -> a shallow copy of D. """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __init__(self, default_factory=None, **kwargs): # known case of _collections.defaultdict.__init__
        """
        defaultdict(default_factory[, ...]) --> dict with default factory
        
        The default factory is called without arguments to produce
        a new value when a key is not present, in __getitem__ only.
        A defaultdict compares equal to a dict with the same items.
        All remaining arguments are treated the same as if they were
        passed to the dict constructor, including keyword arguments.
        
        # (copied from class doc)
        """
        pass

    def __missing__(self, key): # real signature unknown; restored from __doc__
        """
        __missing__(key) # Called by __getitem__ for missing key; pseudo-code:
          if self.default_factory is None: raise KeyError((key,))
          self[key] = value = self.default_factory()
          return value
        """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """Factory for default value called by __missing__()."""
複製代碼

四、可命名元組(namedtuple) 

根據nametuple能夠建立一個包含tuple全部功能以及其餘功能的類型。

1
2
3
import  collections
  
Mytuple  =  collections.namedtuple( 'Mytuple' ,[ 'x' 'y' 'z' ])
複製代碼
class Mytuple(__builtin__.tuple)
 |  Mytuple(x, y)
 |  
 |  Method resolution order:
 |      Mytuple
 |      __builtin__.tuple
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __getnewargs__(self)
 |      Return self as a plain tuple.  Used by copy and pickle.
 |  
 |  __getstate__(self)
 |      Exclude the OrderedDict from pickling
 |  
 |  __repr__(self)
 |      Return a nicely formatted representation string
 |  
 |  _asdict(self)
 |      Return a new OrderedDict which maps field names to their values
 |  
 |  _replace(_self, **kwds)
 |      Return a new Mytuple object replacing specified fields with new values
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  _make(cls, iterable, new=<built-in method __new__ of type object>, len=<built-in function len>) from __builtin__.type
 |      Make a new Mytuple object from a sequence or iterable
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(_cls, x, y)
 |      Create new instance of Mytuple(x, y)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      Return a new OrderedDict which maps field names to their values
 |  
 |  x
 |      Alias for field number 0
 |  
 |  y
 |      Alias for field number 1
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  _fields = ('x', 'y')
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from __builtin__.tuple:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  __sizeof__(...)
 |      T.__sizeof__() -- size of T in memory, in bytes
 |  
 |  count(...)
 |      T.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.

Mytuple
複製代碼

五、雙向隊列(deque)

一個線程安全的雙向隊列

複製代碼
class deque(object):
    """
    deque([iterable[, maxlen]]) --> deque object
    
    Build an ordered collection with optimized access from its endpoints.
    """
    def append(self, *args, **kwargs): # real signature unknown
        """ Add an element to the right side of the deque. """
        pass

    def appendleft(self, *args, **kwargs): # real signature unknown
        """ Add an element to the left side of the deque. """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from the deque. """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ D.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, *args, **kwargs): # real signature unknown
        """ Extend the right side of the deque with elements from the iterable """
        pass

    def extendleft(self, *args, **kwargs): # real signature unknown
        """ Extend the left side of the deque with elements from the iterable """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """ Remove and return the rightmost element. """
        pass

    def popleft(self, *args, **kwargs): # real signature unknown
        """ Remove and return the leftmost element. """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """ D.remove(value) -- remove first occurrence of value. """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ D.reverse() -- reverse *IN PLACE* """
        pass

    def rotate(self, *args, **kwargs): # real signature unknown
        """ Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left. """
        pass

    def __copy__(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a deque. """
        pass

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iadd__(self, y): # real signature unknown; restored from __doc__
        """ x.__iadd__(y) <==> x+=y """
        pass

    def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__
        """
        deque([iterable[, maxlen]]) --> deque object
        
        Build an ordered collection with optimized access from its endpoints.
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __reversed__(self): # real signature unknown; restored from __doc__
        """ D.__reversed__() -- return a reverse iterator over the deque """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -- size of D in memory, in bytes """
        pass

    maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """maximum size of a deque or None if unbounded"""


    __hash__ = None
複製代碼

注:既然有雙向隊列,也有單項隊列(先進先出 FIFO )

複製代碼
class Queue:
    """Create a queue object with a given maximum size.

    If maxsize is <= 0, the queue size is infinite.
    """
    def __init__(self, maxsize=0):
        self.maxsize = maxsize
        self._init(maxsize)
        # mutex must be held whenever the queue is mutating.  All methods
        # that acquire mutex must release it before returning.  mutex
        # is shared between the three conditions, so acquiring and
        # releasing the conditions also acquires and releases mutex.
        self.mutex = _threading.Lock()
        # Notify not_empty whenever an item is added to the queue; a
        # thread waiting to get is notified then.
        self.not_empty = _threading.Condition(self.mutex)
        # Notify not_full whenever an item is removed from the queue;
        # a thread waiting to put is notified then.
        self.not_full = _threading.Condition(self.mutex)
        # Notify all_tasks_done whenever the number of unfinished tasks
        # drops to zero; thread waiting to join() is notified to resume
        self.all_tasks_done = _threading.Condition(self.mutex)
        self.unfinished_tasks = 0

    def task_done(self):
        """Indicate that a formerly enqueued task is complete.

        Used by Queue consumer threads.  For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items
        have been processed (meaning that a task_done() call was received
        for every item that had been put() into the queue).

        Raises a ValueError if called more times than there were items
        placed in the queue.
        """
        self.all_tasks_done.acquire()
        try:
            unfinished = self.unfinished_tasks - 1
            if unfinished <= 0:
                if unfinished < 0:
                    raise ValueError('task_done() called too many times')
                self.all_tasks_done.notify_all()
            self.unfinished_tasks = unfinished
        finally:
            self.all_tasks_done.release()

    def join(self):
        """Blocks until all items in the Queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer thread calls task_done()
        to indicate the item was retrieved and all work on it is complete.

        When the count of unfinished tasks drops to zero, join() unblocks.
        """
        self.all_tasks_done.acquire()
        try:
            while self.unfinished_tasks:
                self.all_tasks_done.wait()
        finally:
            self.all_tasks_done.release()

    def qsize(self):
        """Return the approximate size of the queue (not reliable!)."""
        self.mutex.acquire()
        n = self._qsize()
        self.mutex.release()
        return n

    def empty(self):
        """Return True if the queue is empty, False otherwise (not reliable!)."""
        self.mutex.acquire()
        n = not self._qsize()
        self.mutex.release()
        return n

    def full(self):
        """Return True if the queue is full, False otherwise (not reliable!)."""
        self.mutex.acquire()
        n = 0 < self.maxsize == self._qsize()
        self.mutex.release()
        return n

    def put(self, item, block=True, timeout=None):
        """Put an item into the queue.

        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until a free slot is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Full exception if no free slot was available within that time.
        Otherwise ('block' is false), put an item on the queue if a free slot
        is immediately available, else raise the Full exception ('timeout'
        is ignored in that case).
        """
        self.not_full.acquire()
        try:
            if self.maxsize > 0:
                if not block:
                    if self._qsize() == self.maxsize:
                        raise Full
                elif timeout is None:
                    while self._qsize() == self.maxsize:
                        self.not_full.wait()
                elif timeout < 0:
                    raise ValueError("'timeout' must be a non-negative number")
                else:
                    endtime = _time() + timeout
                    while self._qsize() == self.maxsize:
                        remaining = endtime - _time()
                        if remaining <= 0.0:
                            raise Full
                        self.not_full.wait(remaining)
            self._put(item)
            self.unfinished_tasks += 1
            self.not_empty.notify()
        finally:
            self.not_full.release()

    def put_nowait(self, item):
        """Put an item into the queue without blocking.

        Only enqueue the item if a free slot is immediately available.
        Otherwise raise the Full exception.
        """
        return self.put(item, False)

    def get(self, block=True, timeout=None):
        """Remove and return an item from the queue.

        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until an item is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Empty exception if no item was available within that time.
        Otherwise ('block' is false), return an item if one is immediately
        available, else raise the Empty exception ('timeout' is ignored
        in that case).
        """
        self.not_empty.acquire()
        try:
            if not block:
                if not self._qsize():
                    raise Empty
            elif timeout is None:
                while not self._qsize():
                    self.not_empty.wait()
            elif timeout < 0:
                raise ValueError("'timeout' must be a non-negative number")
            else:
                endtime = _time() + timeout
                while not self._qsize():
                    remaining = endtime - _time()
                    if remaining <= 0.0:
                        raise Empty
                    self.not_empty.wait(remaining)
            item = self._get()
            self.not_full.notify()
            return item
        finally:
            self.not_empty.release()

    def get_nowait(self):
        """Remove and return an item from the queue without blocking.

        Only get an item if one is immediately available. Otherwise
        raise the Empty exception.
        """
        return self.get(False)

    # Override these methods to implement other queue organizations
    # (e.g. stack or priority queue).
    # These will only be called with appropriate locks held

    # Initialize the queue representation
    def _init(self, maxsize):
        self.queue = deque()

    def _qsize(self, len=len):
        return len(self.queue)

    # Put a new item in the queue
    def _put(self, item):
        self.queue.append(item)

    # Get an item from the queue
    def _get(self):
        return self.queue.popleft()
複製代碼

 

OS模塊

用於提供系統級別的操做:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
os.getcwd()                 獲取當前工做目錄,即當前python腳本工做的目錄路徑
os.chdir( "dirname" )         改變當前腳本工做目錄;至關於shell下cd
os.curdir                   返回當前目錄: ( '.' )
os.pardir                   獲取當前目錄的父目錄字符串名:( '..' )
os.makedirs( 'dir1/dir2' )    可生成多層遞歸目錄
os.removedirs( 'dirname1' )   若目錄爲空,則刪除,並遞歸到上一級目錄,如若也爲空,則刪除,依此類推
os.mkdir( 'dirname' )         生成單級目錄;至關於shell中mkdir dirname
os.rmdir( 'dirname' )         刪除單級空目錄,若目錄不爲空則沒法刪除,報錯;至關於shell中rmdir dirname
os.listdir( 'dirname' )       列出指定目錄下的全部文件和子目錄,包括隱藏文件,並以列表方式打印
os.remove()                 刪除一個文件
os.rename( "oldname" , "new" )  重命名文件 / 目錄
os.stat( 'path/filename' )    獲取文件 / 目錄信息
os.sep                      操做系統特定的路徑分隔符,win下爲 "\\",Linux下爲" / "
os.linesep                  當前平臺使用的行終止符,win下爲 "\t\n" ,Linux下爲 "\n"
os.pathsep                  用於分割文件路徑的字符串
os.name                     字符串指示當前使用平臺。win - > 'nt' ; Linux - > 'posix'
os.system( "bash command" )   運行shell命令,直接顯示
os.environ                  獲取系統環境變量
os.path.abspath(path)       返回path規範化的絕對路徑
os.path.split(path)         將path分割成目錄和文件名二元組返回
os.path.dirname(path)       返回path的目錄。其實就是os.path.split(path)的第一個元素
os.path.basename(path)      返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素
os.path.exists(path)        若是path存在,返回 True ;若是path不存在,返回 False
os.path.isabs(path)         若是path是絕對路徑,返回 True
os.path.isfile(path)        若是path是一個存在的文件,返回 True 。不然返回 False
os.path.isdir(path)         若是path是一個存在的目錄,則返回 True 。不然返回 False
os.path.join(path1[, path2[, ...]])  將多個路徑組合後返回,第一個絕對路徑以前的參數將被忽略
os.path.getatime(path)      返回path所指向的文件或者目錄的最後存取時間
os.path.getmtime(path)      返回path所指向的文件或者目錄的最後修改時間

  

hashlib

用於加密相關的操做,代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import  hashlib
  
# ######## md5 ########
hash  =  hashlib.md5()
# help(hash.update)
hash .update(bytes( 'admin' , encoding = 'utf-8' ))
print ( hash .hexdigest())
print ( hash .digest())
  
  
######## sha1 ########
  
hash  =  hashlib.sha1()
hash .update(bytes( 'admin' , encoding = 'utf-8' ))
print ( hash .hexdigest())
  
# ######## sha256 ########
  
hash  =  hashlib.sha256()
hash .update(bytes( 'admin' , encoding = 'utf-8' ))
print ( hash .hexdigest())
  
  
# ######## sha384 ########
  
hash  =  hashlib.sha384()
hash .update(bytes( 'admin' , encoding = 'utf-8' ))
print ( hash .hexdigest())
  
# ######## sha512 ########
  
hash  =  hashlib.sha512()
hash .update(bytes( 'admin' , encoding = 'utf-8' ))
print ( hash .hexdigest())

以上加密算法雖然依然很是厲害,但時候存在缺陷,即:經過撞庫能夠反解。因此,有必要對加密算法中添加自定義key再來作加密。

1
2
3
4
5
6
7
import  hashlib
  
# ######## md5 ########
  
hash  =  hashlib.md5(bytes( '898oaFs09f' ,encoding = "utf-8" ))
hash .update(bytes( 'admin' ,encoding = "utf-8" ))
print ( hash .hexdigest())

python內置還有一個 hmac 模塊,它內部對咱們建立 key 和 內容 進行進一步的處理而後再加密

1
2
3
4
5
import  hmac
  
=  hmac.new(bytes( '898oaFs09f' ,encoding = "utf-8" ))
h.update(bytes( 'admin' ,encoding = "utf-8" ))
print (h.hexdigest())
複製代碼
import hashlib

def hash(pwd):
    hash = hashlib.md5(bytes("zhangyanlin",encoding='utf-8'))
    hash.update(bytes(pwd,encoding='utf-8'))
    return hash.hexdigest()

def login(username,passwd):
    with open("db",'r',encoding="utf-8") as f:
        for i in f:
            i  = i.strip().split("|")
            if i[0] == username and i[1] == hash(passwd):
                return True

def zc_login(username,passwd):
    with open("db","a",encoding='utf-8') as f:
        use_pwd =  username + "|" + hash(passwd) + "\n"
        f.write(use_pwd)
        return True


choice = input("1.登陸;2.註冊 \n請您選擇:")
if choice == "1":
    for i in range(3):
        user = input("請輸入用戶名:")
        pwd  = input("請輸入密碼:")
        login_1 = login(user,pwd)
        if login_1:
            print("登陸成功")
            break
        else:
            print('登陸失敗!')
            continue
elif choice == "2":
    user = input("請輸入用戶名:")
    pwd  = input("請輸入密碼:")
    login_2 = zc_login(user,pwd)
    if login_2:
        print("註冊成功!")
複製代碼

 

XML

XML是實現不一樣語言或程序之間進行數據交換的協議,XML文件格式以下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<data>
     <country name = "Liechtenstein" >
         <rank updated = "yes" > 2 < / rank>
         <year> 2023 < / year>
         <gdppc> 141100 < / gdppc>
         <neighbor direction = "E"  name = "Austria"  / >
         <neighbor direction = "W"  name = "Switzerland"  / >
     < / country>
     <country name = "Singapore" >
         <rank updated = "yes" > 5 < / rank>
         <year> 2026 < / year>
         <gdppc> 59900 < / gdppc>
         <neighbor direction = "N"  name = "Malaysia"  / >
     < / country>
     <country name = "Panama" >
         <rank updated = "yes" > 69
相關文章
相關標籤/搜索