python踩的坑(持续更新)

0x01 多线程不生效

使用ThreadPoolExecutor线程池,并使用submit提交调用函数
开始调用写法

from concurrent.futures import ThreadPoolExecutor
from concurrent import futures

pool = ThreadPoolExecutor(20)
result = pool.submit(test, arg1).result

简单说下两句的用法,第一句是设置线程池最大线程数为20,第二句是多线程调用函数test,并且test函数有个参数是arg1,.result是获取函数调用以后得返回结果,这样调用的一个问题是提交以后会等到有结果以后才会重新创建一个线程
正确的用法

from concurrent.futures import ThreadPoolExecutor
from concurrent import futures

pool = ThreadPoolExecutor(20)
task = pool.submit(test, arg1)
        tread.append(task)
    for t in futures.as_completed(tread):
        try:
            result = t.result()
        except Exception as e:
            print("线程执行错误:{}".format(e))

使用as_completed()函数判断线程是否执行完成,然后再获取result

0x02 读文件出先编码错误

使用二进制读取再转换为UTF-8

f = open(file, 'rb')
for line in f.readlines():
	line = line.decode("utf-8")
    line = line.strip()

0x03 在插入mysql数据库时先检查数据库中是否有这条数据

原先得做法
这里就不贴代码了,分为两步,先会用select查询以便,没有再执行insert语句
下面通过复合语句
复合语句

def no_repeat_insert(self, user, password, userid):
    '''
    复合语句去重插入,当数据库不存在userid等于传入userid时插入
    更改sql语句,传入参数,execute函数第二个参数
    '''
    insert_sql = "INSERT INTO test (`user`, `password`, `userid`) select %s, %s, %s from" \
                 " dual WHERE not exists (select * from test where `userid` = %s"
    cursor = self.db_connect.cursor()
    cursor.execute(insert_sql, (user, password, userid, userid))

0x04 UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0x83 in position 1:invalid start byte

因为header里面这条的原因 “Accept-Encoding’: ‘gzip, deflate”
写爬虫程序时候还是不要写’Accept-Encoding’: 'gzip, deflate’了,就让服务器传原始文件过来吧,不用压缩了。

你可能感兴趣的:(python踩坑日记)