语法检查
pylint 是一个能够检查Python编码质量、编码规范的工具。它分析 Python 代码中的错误,查找不符合代码风格标准(Pylint 默认使用的代码风格是 PEP 8)和有潜在问题的代码。
个人认为正确性比风格更加重要,不妨大材小用,执行脚本之前,都使用pylint进行语法检查一下。
1 2
| pip install pylint pylint test.py
|
导入自定义模块
全局导入
自己新建了一个模块,怎样让它可以被全局引用?答:导入自定义模块。
具体操作方法:
1、进入 xxx/python3/lib/python3.6/site-packages 目录
2、新建 yyy.pth 文件,写入自定义模块的路径
1
| /home/voidking/scripts/vktools/
|
详情参考python之使用.pth文件导入自定义模块
指定文件导入
自己新建了一个模块a,路径不同的情况下,怎样让它被模块b引用?答:使用 sys.path.append 函数。
1 2
| sys.path.append('/path/to/a')
|
查找文件
在指定目录中,根据文件前缀查找文件。
1 2 3 4 5 6 7 8
| import glob
def find_files_by_prefix(prefix, dir_path): file_list = list() file_pattern = os.path.join(dir_path, '{}*'.format(prefix)) for f in glob.glob(file_pattern): file_list.append(f) return file_list
|
删除目录和文件
封装几个简单函数,删除目录和文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import os import shutil
def remove_dir(dir_path): if os.path.exists(dir_path): os.removedirs(dir_path)
def remove_file(file_path): if os.path.exists(file_path): os.remove(file_path)
def remove_dir_and_file(dir_path): if os.path.exists(dir_path): shutil.rmtree(dir_path)
|
url特殊字符转义
1 2 3
| from urllib import parse labelselector = parse.quote('app_id=voidking,env in (test,online)') url = f'https://www.voidking.com?labelselector={labelselector}'
|
特殊字符对应url编码表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| 空格 : %20 " : %22 # : %23 % : %25 & : %26 ( : %28 ) : %29 + : %2B , : %2C / : %2F : : %3A ; : %3B < : %3C = : %3D > : %3E ? : %3F @ : %40 \ : %5C | : %7C
|
安装pip
一些情况下,在安装python时没有默认安装pip,这时就需要手动安装。
1 2 3 4 5 6
| python -m ensurepip
wget https://bootstrap.pypa.io/get-pip.py python get-pip.py -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
|
装饰器
实现一个装饰器,功能:只要函数里传了name参数,且name参数的值为haojin,那么就把这个值替换为voidking。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from functools import wraps def haojin_to_voidking(func): @wraps(func) def decorated(*args, **kwargs): if 'name' in kwargs and kwargs['name'] == 'haojin': kwargs['name'] = 'voidking' return func(*args, **kwargs) return decorated
@haojin_to_voidking def print_name(name): print(name)
print_name(name='haojin')
|
Python镜像选择
我们可能倾向于选择一个小镜像Alpine,但是这会导致更长的构建时间和模糊的错误,因此不建议。
推荐的镜像:
- ubuntu:18.04
- ubuntu:20.04
- python:3.7.10-slim-buster (基于Debian buster)
Debian buster软件包查找地址为Debian - buster版面列表,找到软件包后使用apt install安装即可,例如安装mysql client
1 2
| apt install default-libmysqlclient-dev apt install default-mysql-client
|
参考文档:适用于您的 Python 应用程序的最佳 Docker 基础镜像
启动python web服务器
使用sz传输大文件,有时候会被中断。这时我们可以启动一个web服务,把大文件作为静态资源下载。
1 2
| python -m SimpleHTTPServer 9999 python3 -m http.server 9999
|
然后浏览器输入ip:port,即可下载文件。
pyc反编译py
1 2
| pip install uncompyle6 uncompyle6 -o filename.py filename.pyc
|
参考文档