一个计算机技术爱好者与学习者

0%

Python小技巧

1. 查找文件

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

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

2. 删除目录和文件

封装几个简单函数,删除目录和文件。

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)

3. 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

4. 装饰器

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

5. 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 基础镜像

6. 启动python web服务器

使用sz传输大文件,有时候会被中断。这时我们可以启动一个web服务,把大文件作为静态资源下载。

1
2
python -m SimpleHTTPServer 9999
python3 -m http.server 9999

然后浏览器输入ip:port,即可下载文件。

7. py编译为pyc

1、批量编译整个项目

1
python -m compileall project_dir

2、移动位置和重命名
编译后的 pyc 文件,放在 __pycache__ 目录中,需要移动到上一层目录。
编译后的 pyc 文件名中,会带着解释器的版本(例如 cpython-37),会导致找不到模块,因此需要将所有 pyc 文件重命名。

1
2
3
find project_dir -type d -name "__pycache__" -exec sh -c 'mv "$0"/* "$(dirname "$0")"' {} \;
find project_dir -name "*.pyc" -exec sh -c 'mv "$0" "${0%.cpython-37.pyc}.pyc"' {} \;
#for file in *.cpython-37.pyc;do mv "$file" "${file%.cpython-37.pyc}.pyc";done

3、删除py文件

1
find project_dir -name "*.py" | xargs rm -fv

4、启动项目
假设原启动命令为 python main.py ,那么编译后的启动命令为

1
python main.pyc

8. pyc反编译py

1
2
pip install uncompyle6
uncompyle6 -o filename.py filename.pyc

9. py文件加密

1
2
pip install pyarmor
pyarmor gen test.py

参考文档:

10. 参考文档

  • 本文作者: 好好学习的郝
  • 原文链接: https://www.voidking.com/dev-python-tricks/
  • 版权声明: 本文采用 BY-NC-SA 许可协议,转载请注明出处!源站会即时更新知识点并修正错误,欢迎访问~
  • 微信公众号同步更新,欢迎关注~