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()作用

进程池

提供指定数量的进程供用户调用




猜你喜欢

转载自blog.csdn.net/RikkaTakanashi/article/details/80309140