0%

Python小技巧

查找文件

在指定目录中,根据文件前缀查找文件。

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

装饰器

实现一个装饰器,功能:只要函数里传了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)

Ubuntu/Debian的默认软件安装源都比较慢,因此最好先替换成国内软件安装源,详情参考《Ubuntu/Debian替换软件安装源》

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

参考文档

  • 本文作者: 好好学习的郝
  • 本文链接: https://www.voidking.com/dev-python-tricks/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!源站会及时更新知识点及修正错误,阅读体验也更好。欢迎分享,欢迎收藏~