python3错误集不定时更新

snake

Photo by Austin Lowman on Unsplash

读写文件编码问题

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xae in position 553: illegal multibyte sequence

解决,添加指定编码

1
2
3
4
5
6
7
8
9
10
# 原
with open(filename, mode = 'r') as f:
for line in f:
print(repr(line))


# 修改
with open(filename, encoding='utf-8', mode = 'r') as f:
for line in f:
print(repr(line))

参考:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xaa in position 553: illegal multibyte sequence · Issue #37 · rkern/line_profiler

YAML.load错误

YAMLLoadWarning: calling yaml.load() without Loader=… is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.

1
2
3
4
# 原
yaml.load(input)
# 修改
yaml.load(input, Loader=yaml.FullLoader)

参考:yaml.load()时总是出现警告:YAMLLoadWarning: calling yaml.load() without Loader=…_网络_如果没有梦想,那跟咸鱼有什么分别-CSDN博客

YAML模块找不到

ModuleNotFoundError: No module named ‘yaml’

解决,pip install pyyaml

参考:ModuleNotFoundError: No module named ‘yaml’ · Issue #291 · yaml/pyyaml

base64

a bytes-like object is required, not ‘str’

1
2
3
4
5
# 原
email['html'] = base64.b64encode(email.get('html'))

# 修改为
email['html'] = base64.b64encode(email.get('html').encode('utf-8')).decode('utf-8')

参考:TypeError: a bytes-like object is required, not ‘str’ (smtp_sen_email) · Issue #7 · sendpulse/sendpulse-rest-api-python

str转dict/如何将字符串转换成字典dict类型

1
2
import json
temp = json.loads(str)

Mysql-Python

安装Mysql数据库

1.pip install Mysql-Python

1
2
3
building '_mysql' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

问题:python很多包都是通过C或C++写的,因此需要C++编译工具,

解决:安装C++编译或安装最新版的Visual Studio或是安装已经编译好的包

Mysql则需要安装mysql-python和mysqlclient

1
2
3
4
5
# mysql-python
https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
# mysqlclient
https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient

mysql-python

根据系统版本下载win_amd64或win32位的编译包,使用pip安装#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl
# 如果出现下面错误
ERROR: MySQL_python-1.2.5-cp27-none-win32.whl is not a supported wheel on this p
latform.
# 通过修改文件名来实现安装,文件名则根据Python版本进行修改,如我的版本是3.7
# 将
MySQL_python-1.2.5-cp27-none-win_amd64.whl
# 改成
MySQL_python-1.2.5-cp37-none-win_amd64.whl
# 即可
D:\Users\Administrator\Desktop\testss>python -V
Python 3.7.0

# D:\testss>python -V
Python 3.7.0

# D:\testss>pip install D:\testss\mysqlclient-1.4.6-cp37-cp37m-win_amd64.whl
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Processing d:\testss\mysqlclient-1.4.6-cp37-cp37m-win_amd64.whl
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.4.6

改名

ip2Region报错 Index pointer not found

环境,Windows7,python3.7.0,ip2Region2.2.0,Flask1.1.0

情况,使用默认b-tree算法,配合Flask,第一次出现正常结果,刷新后则出现Index pointer not found,指针错误

原因,Flask生命周期或是其他原因导致ip2Region被关闭,(即使没有写searcher.close())

解决,更换其他算法即可,如binarySearch算法或是memory算法,如下

1
2
3
4
5
6
7
8
9
10
# 更换算法
algorithm = "memory"
searcher = Ip2Region(dbFile)
try:
# 算法使用的方法也要更换,如memorySearch,binarySearch
data = searcher.memorySearch(ip)
except Exception as e:
print(e)
# 跟换其他算法后关不关闭都不影响二次使用
searcher.close()

Flask

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 获取参数,get,post
# POST
request.form['username']

# GET
request.args.get('key', '')

# 自定义404错误,500等错误异常界面
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404

————————————————
参考链接:https://flask.palletsprojects.com/en/1.1.x/quickstart/#redirects-and-errors

三目运算

python中的三元表达式(三目运算符)
x = "变量1" if a>b else "变量2"

编码

Non-UTF-8 code starting with ‘\xe5’ in file

1
2
3
4
5
6
运行出现	Non-UTF-8 code starting with '\xe5' in file
解决,头部添加
# coding=utf8

————————————————
参考链接:https://stackoverflow.com/questions/23092176/syntaxerror-non-utf-8-code-starting-with-x91

环境变量

‘pip’ 不是内部或外部命令,也不是可运行的程序

解:[python3以上适用] 将python目录下的Scripts添加到环境变量,如下目录

1
C:\Users\Administrator\AppData\Local\Programs\Python\Python37\Scripts

‘python’ 不是内部或外部命令,也不是可运行的程序

解:将python目录添加到环境变量,如下目录

1
C:\Users\Administrator\AppData\Local\Programs\Python\Python37\

str 与 bytes 之间的转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# bytes object
b = b"example"

# str object
s = "example"

# str to bytes
bytes(s, encoding = "utf8")

# bytes to str
str(b, encoding = "utf-8")

# an alternative method
# str to bytes
str.encode(s)

# bytes to str
bytes.decode(b)
# ————————————————
# 日期:2020/12/11
# 参考链接:https://blog.csdn.net/yatere/article/details/6606316

Python获取数组列表下表

1
2
for i in range(len(list_a)):
print(list[i],i)

Python 命令行参数

1
2
3
4
5
6
7
8
9
10
11
python test.py arg1 arg2 arg3
Python 中也可以使用 sys 的 sys.argv 来获取命令行参数:

sys.argv 是命令行参数列表。

len(sys.argv) 是命令行参数个数。

注:sys.argv[0] 表示脚本名。
# ————————————————
# 日期:2021-02-21
# 参考链接:https://www.runoob.com/python/python-command-line-arguments.html

生成EXE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
pip install pyinstaller
打包方法:
使用终端,进入工程所在文件夹,然后使用pyinstaller [opts] yourprogram.py命令
opts:
-F 指定打包后只生成一个exe格式的文件(建议写上这个参数)
-D –onedir 创建一个目录,包含exe文件,但会依赖很多文件(默认选项)
-c –console, –nowindowed 使用控制台,无界面(默认)
-w –windowed, –noconsole 使用窗口,无控制台
-p 添加搜索路径,让其找到对应的库。
-i 改变生成程序的icon图标
举例:
在你的D:\project下有个python程序叫test.py
同时你也在这个目录下放了一个你喜欢的hello.ico的ico图标文件
那么这个时候你就会愉快的利用终端敲下如下命令:
pyinstaller -F -i hello.ico test.py
以上命令打包出来的.exe运行时会弹出终端,如果不想要这个小黑框可加上 -w 命令,例如:
pyinstaller -F -i hello.ico test.py -w

命令运行结束后你惊奇发现,在D:\project多了pycache、build、dist三个文件夹和一个test.spec文件
这时你进到dist文件夹下,里面就有你的test.exe
# ————————————————
# 日期:2021-02-21
# 参考链接:https://www.jianshu.com/p/9718b35cc323

SQLite压缩清空回收站

压缩Sqlite数据文件大小,解决数据删除后占用空间不变的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
VACUUM

VACUUM 命令通过复制主数据库中的内容到一个临时数据库文件,然后清空主数据库,并从副本中重新载入原始的数据库文件。这消除了空闲页,把表中的数据排列为连续的,另外会清理数据库文件结构。

如果表中没有明确的整型主键(INTEGER PRIMARY KEY),VACUUM 命令可能会改变表中条目的行 ID(ROWID)。VACUUM 命令只适用于主数据库,附加的数据库文件是不可能使用 VACUUM 命令。

如果有一个活动的事务,VACUUM 命令就会失败。VACUUM 命令是一个用于内存数据库的任何操作。由于 VACUUM 命令从头开始重新创建数据库文件,所以 VACUUM 也可以用于修改许多数据库特定的配置参数。
手动 VACUUM
下面是在命令提示符中对整个数据库发出 VACUUM 命令的语法:

$sqlite3 database_name "VACUUM;"
您也可以在 SQLite 提示符中运行 VACUUM,如下所示:

sqlite> VACUUM;
您也可以在特定的表上运行 VACUUM,如下所示:

sqlite> VACUUM table_name;
!!!一定概率破坏数据库文件完整性。
# ————————————————
# 日期:2021-02-21
# 参考链接:https://www.runoob.com/sqlite/sqlite-vacuum.html

pip

1
2
3
4
5
6
7
8
9
# 生成requirements.txt 文件
pip freeze > requirements.txt

# 安装到当前目录或指定目录
pip install -t ./ requests

# 读取requirements.txt文件并安装到当前目录或指定目录
pip install -r requirements.txt -t ./

文件是否存在

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 判断文件是否存在
import os
os.path.exists(test_file.txt)
#True

os.path.exists(no_exist_file.txt)
#False

# 判断文件夹是否存在
import os
os.path.exists(test_dir)
#True

os.path.exists(no_exist_dir)
#False

# 只检查文件
import os
os.path.isfile("test-data")
# 判断文件是否可做读写操作
# os.F_OK: 检查文件是否存在;
# os.R_OK: 检查文件是否可读;
# os.W_OK: 检查文件是否可以写入;
# os.X_OK: 检查文件是否可以执行
# 该方法通过判断文件路径是否存在和各种访问模式的权限返回True或者False。

import os
if os.access("/file/path/foo.txt", os.F_OK):
print "Given file path is exist."

if os.access("/file/path/foo.txt", os.R_OK):
print "File is accessible to read"

if os.access("/file/path/foo.txt", os.W_OK):
print "File is accessible to write"

if os.access("/file/path/foo.txt", os.X_OK):
print "File is accessible to execute"

#使用Python3版本中内建pathlib模块
#检查路径是否存在
path = pathlib.Path("path/file")
path.exist()

#检查路径是否是文件
path = pathlib.Path("path/file")
path.is_file()
# ————————————————
# 日期:2021-03-01
# 参考链接:https://www.cnblogs.com/jhao/p/7243043.html

是对象不是map

fastapi sqlalchemy

TypeError: ‘People’ object is not subscriptable

is not mapped

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class People(BaseModel):
name: str
age: int

@app.post('/insert')
def insert(people: People):
# 错误的使用
print(people['name'])
# 正确的使用
print(people.name)
msg = f'name:{people.name},age:{age}'
return {'success': True, 'msg': msg}

参考: