天天看點

python内置子產品(二)

-------------------接《python内置子產品(一)》--------------------------------

四、json、pickle 資料序列化

    用于序列化的兩個子產品

    • json,用于字元串 和 python資料類型間進行轉換
    • pickle,用于python特有的類型 和 python的資料類型間進行轉換

        Json子產品提供了四個功能:dumps、dump、loads、load

        pickle子產品提供了四個功能:dumps、dump、loads、load

        # pickle.dumps 通過特殊的形式将資料轉換成隻有python能認識的字元串

    >>> import pickle

    >>> data = {'lihongye1':'pwd1','lihongye2':'pwd2'}

    >>> p_str = pickle.dumps(data)

    >>> print(p_str)

    或将字元串轉換成隻有python能認識的字元串存儲在檔案中

    test = { 'user':'lihongye','pwd':'pwd1','num':'123'}

    import pickle

    fw = open('test_file','wb')

    fw.write(pickle.dumps(test))

    通過pickle.loads 将字元串轉成原資料形式

    fr = open('test_file','rb')

    frp = pickle.load(fr)

    print(frp)

    # 也可通過json.dumps方式将資料轉成所有程式都能認識的字元串格式并寫入檔案

    test = { 'user':'lihongye','pwd':'pwd1','num':'123'}

    import json

    fw = open('test_file','w')

    fw.write(json.dumps(test))

    通過json.loads方式将字元串轉換成原資料格式

    fr = open('test_file','r')

    frp = json.load(fr)

五、 random

     随機數

     >>> import random

        >>> random.random()           # 随機小數

        0.7558096251338481

        >>> random.randint(1,3)       # 有範圍的随機數1-3

        2

        >>> random.randrange(1,10)    # 有範圍的随機數1-9

        1

     随機驗證碼執行個體

        import  random

        check_code = ''

        for i in range(4):

            current = random.randint(0,4)

            if current != i:

                tmp = str(chr(random.randint(65,90)))

            else:

                tmp = random.randint(0,9)

            check_code += str(current)

        print(check_code)

六、 subprocess 執行系統指令

    call 執行系統指令,如果指令正确則傳回狀态碼,否則抛出異常

            >>> res = subprocess.call(['ls','-l'],shell=False)

             >>> res = subprocess.call(['ls -l'],shell=True)

            shell = True 調用系統平台執行指令;

      check_call 執行指令,如果執行狀态碼是 0 ,則傳回0,否則抛異常

        >>> res = subprocess.check_call(['ls -l'],shell=True)   結果是0

             >>> res = subprocess.check_call(['ls-l'],shell=True)    結果異常

      check_output 執行指令,如果執行狀态碼是 0 ,則傳回結果,否則抛異常     

             >>> res = subprocess.check_ouput(['ls -l'],shell=True)   傳回執行結果

             >>> res = subprocess.check_ouput(['ls-l'],shell=True)   結果異常

      Popen   用于執行更加複雜的系統指令

         可用參數:

             args:      shell指令,可以是字元串或者序列類型(如:list,元組)

             bufsize:   指定緩沖。0 無緩沖,1 行緩沖,其他 緩沖區大小,負值 系統緩沖

             stdin, stdout, stderr:分别表示程式的标準輸入、輸出、錯誤句柄

             preexec_fn:隻在Unix平台下有效,用于指定一個可執行對象(callable object),它将在

                         子程序運作之前被調用

             close_sfs: 在windows平台下,如果close_fds被設定為True,則新建立的子程序将不會繼承

                         父程序的輸入、輸出、錯誤管道。是以不能将close_fds設定為True同時重定向

                         子程序的标準輸入、輸出與錯誤(stdin, stdout, stderr)。

             shell:同上cwd:用于設定子程序的目前目錄env:用于指定子程序的環境變量。如果env =                               None,子程序的環境變量将從父程序中繼承。universal_newlines:不同系統的換行

                    符不同,True -> 同意使用 \nstartupinfo與createionflags隻在windows下有效将被

                    傳遞給底層的CreateProcess()函數,用于設定子程序的一些屬性,如:主視窗的外觀,

                    程序的優先級等等                            

            >>>res=subprocess.Popen(['python3'],stdin=subprocess.PIPE,                                                 stdout=subprocess.PIPE,stderr=subprocess.PIPE)

            >>> res.stdin.write(b"print('hello1')\n")

            16

            >>> res.stdin.write(b"print('hello2')\n")

            >>> res.stdin.write(b"print('hello3')\n")

            >>> ret = res.communicate(timeout=10)

            >>> print(ret)

            (b'hello1\nhello2\nhello3\n', b'')

                     >>> res.pid

                     5722

                     >>> res.terminate()  會成為僵屍程序并與父程序失去聯系  

                     root      5722  5633  0 10:19 pts/0    00:00:00 [python3] <defunct>

                     >>> res.wait()    完全釋放掉資源

    更多點選這裡

七、 shutil 進階檔案、檔案夾、壓縮包處理子產品

    shutil.copyfileobj(fsrc, fdst[, length])    将檔案内容拷貝到另一檔案

           fsrc 源檔案  fdst 目标檔案  length 每次拷貝長度(可有可無)

        >>> import shutil

        >>> s = open("smtp.py")

        >>> d = open("smtp_copy","w")

        >>> shutil.copyfileobj(s,d,length=20)

>>> d.close()

        [root@python ~]# cat smtp_copy

      shutil.copyfile(src, dst)  拷貝檔案

        >>> shutil.copyfile('smtp.py','smtp')

        [root@python ~]# ls smtp smtp.py 

        smtp  smtp.py

    shutil.copymode(src, dst)  僅拷貝權限。内容、組、使用者均不變

            >>> shutil.copymode('smtp.py','smtp')

        [root@python ~]# ll smtp smtp.py 

        -rw-r--r-- 1 root root 1309 Jan 25 12:02 smtp

        -rw-r--r-- 1 root root 1309 Dec 28 01:30 smtp.py

           shutil.copystat(src, dst)       拷貝狀态的資訊,包括:mode bits, atime, mtime, flags

            >>> shutil.copystat('smtp.py','smtp')

        -rw-r--r-- 1 root root 1309 Dec 28 01:30 smtp

           shutil.copy(src, dst)         拷貝檔案和權限

            >>> shutil.copy('smtp.py','smtp_copy')

        [root@python ~]# ll smtp smtp_copy 

        -rw-r--r-- 1 root root 1309 Jan 25 12:19 smtp_copy

           shutil.copy2(src, dst)        拷貝檔案和狀态資訊

            >>> shutil.copy2('smtp.py','smtp')

            [root@python ~]# ll smtp*

    shutil.ignore_patterns(*patterns)

           shutil.copytree(src, dst, symlinks=False, ignore=None)     遞歸的去拷貝檔案

     >>> shutil.copytree('dir1','dir2')

     [root@python ~]# ll dir1

        total 4

        drwxr-xr-x 3 root root 4096 Jan 25 11:19 dir2

        [root@python ~]# ll dir2

    shutil.rmtree(path[, ignore_errors[, onerror]])     遞歸的去删除檔案

     >>> shutil.rmtree('dir2')

        ls: cannot access dir2: No such file or directory

    shutil.move(src, dst)                遞歸的去移動檔案

     >>> shutil.move('dir1','/tmp')

        [root@python ~]# ll dir1

        ls: cannot access dir1: No such file or directory

        [root@python ~]# ll /tmp/dir1

    shutil.make_archive(base_name, format,...)

        建立壓縮包并傳回檔案路徑,例如:zip、tar

        base_name: 壓縮包的檔案名,也可以是壓縮包的路徑。隻是檔案名時,則儲存至目前

                    目錄,否則儲存至指定路徑,

                    如:www                        =>儲存至目前路徑

                    如:/Users/wupeiqi/www =>儲存至/Users/wupeiqi/

        format:    壓縮包種類,“zip”, “tar”, “bztar”,“gztar”

        root_dir:  要壓縮的檔案夾路徑(預設目前目錄)

        owner:     使用者,預設目前使用者

        group:     組,預設目前組

        logger:    用于記錄日志,通常是logging.Logger對象

    例:

     >>> shutil.make_archive('dir1_archive',format='zip',root_dir='/root/dir1')

        [root@python ~]# ll dir1*

        -rw-r--r-- 1 root root   22 Feb 21 04:04 dir1_archive.zip