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

0%

好好学Python: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. jupyter转python

1
jupyter nbconvert --to python github_stars.ipynb

11. 自动生成python项目的依赖

1、安装pipreqs工具

1
pip install pipreqs

2、生成依赖文件 requirements.txt

1
pipreqs /path/to/project

这种方法,不能保证找到所有的依赖,但是能找到大部分的依赖,已经够用了。

12. pip安装依赖报错

pip install anyjson 报错:

1
2
3
4
5
6
7
8
9
10
11
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple/
Collecting anyjson
Using cached https://pypi.tuna.tsinghua.edu.cn/packages/c3/4d/d4089e1a3dd25b46bebdb55a992b0797cff657b4477bc32ce28038fdecbc/anyjson-0.3.3.tar.gz (8.3 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [1 lines of output]
error in anyjson setup command: use_2to3 is invalid.
[end of output]

这个错误是由于 Python 从 3.10 版本开始,移除了对 use_2to3 支持导致的。
anyjson库在安装时候需要用到这个选项,而在新版本Python中该选项已经被移除,所以出现了此错误。
解决办法是使用老版本的Python,比如Python3.9。

如果使用的是老版本的Python,依然报错了这个错误,那么很可能是 setuptools 版本过高。
解决办法是 setuptools 降版本:

1
pip install 'setuptools<58.0.0'

13. 参考文档

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