Python爬蟲開發與項目實戰讀書筆記__Part1


python中的文件I/O使用方法

f=open(r'D:/test/test.txt','r')

該句中前一個r代表raw string表示對字符串裏的轉義符不進行轉義,寫的什麼就是什麼

後一個r類似於c/c++文件讀寫中的模式 有 'r'讀, 'w'寫, 'a'追加, 'b'二進制, '+'讀/寫 這幾種模式

f.read() 一次全部讀到內存

f.readlines() 一次讀一行,可以與for連用

f.write() 對f所指的文件內容進行寫

記得要加上f.close()


Python

python中有os模塊 但是書中的fork()函數仍然只能在Linux系統下使用,windows中可以使用multiprocessing中的Processing()來進行進程的創建

引用書上的一個例子

import os
from multiprocessing import Process
def run_proc(name):
    print('Child process '+(str)(os.getpid())+" running")
if __name__=='__main__':
    print('Parent process '+(str)(os.getpid()))
    for i in range(5):
        p=Process(target=run_proc,args=(str(i),))
        print('Process will start')
        p.start()
    p.join()
    print('process end')

Process()的變量依次爲函數名以及函數變量

.join()函數是直到當前進程執行完再執行下一個進程

該實例結果

Parent process 10120
Process will start
Process will start
Process will start
Process will start
Process will start
Child process 9632 running
Child process 9908 running
Child process 7644 running
Child process 8340 running
Child process 10064 running

process end

若改變.join()位置

import os
from multiprocessing import Process
def run_proc(name):
    print('Child process '+(str)(os.getpid())+" running")
if __name__=='__main__':
    print('Parent process '+(str)(os.getpid()))
    for i in range(5):
        p=Process(target=run_proc,args=(str(i),))
        print('Process will start')
        p.start()
        p.join()
    print('process end')

結果爲

Parent process 5844
Process will start
Child process 1148 running
Process will start
Child process 10200 running
Process will start
Child process 7868 running
Process will start
Child process 9088 running
Process will start
Child process 9080 running

process end

由此可見.join()作用

進程池

提供指定數量的進程供用戶調用




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章