目录


一、python处理各种格式文件的模块

  • csv
    处理CSV文件。
  • xml.etree.ElementTree,xml.dom,xml.sax
    处理XML文件。前两者会将整个XML文件载入内存,最后一个是循序读入。
  • json
    处理JSON文件。
  • yaml
    处理YAML文件
  • tablib
    处理:CSV,JSON,YAML,Excel,Pandas DataFrame
  • configparser
    处理Windows风格的.ini文件
  • sqlite3
    处理SQLite

二、取得时间戳

import time
now = time.time()
print("Current timestamp is:", now)
  • 1.
  • 2.
  • 3.

三、模拟HTTP的客户端

安装requests第三方包

pip install requests
  • 1.
  • 查询本机公网地址
import requests

print("发送GET请求\n")
url = "https://myip.ipip.net"
response = requests.get(url)
contents = response.text
print(contents)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 书上的两个例子
import json
import sys
import requests

def search(title):
    url = "http://archive.org/advancedsearch.php"
    params = {"q": f"title:({title})",
              "output": "json",
              "fields": "identifier,title",
              "rows": 50,
              "page": 1,}
    resp = requests.get(url, params=params)
    return resp.json()

if __name__ == "__main__":
    title = sys.argv[1]
    data = search(title)
    docs = data["response"]["docs"]
    print(f"Found {len(docs)} items, showing first 10")
    print("identifier\ttitle")
    for row in docs[:10]:
        print(row["identifier"], row["title"], sep="\t")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
"""Find a video at the Internet Archive
by a partial title match and display it."""

import sys
import webbrowser
import requests

def search(title):
    """Return a list of 3-item tuples (identifier,
       title, description) about videos
       whose titles partially match :title."""
    search_url = "https://archive.org/advancedsearch.php"
    params = {
        "q": "title:({}) AND mediatype:(movies)".format(title),
        "fl": "identifier,title,description",
        "output": "json",
        "rows": 10,
        "page": 1,
        }
    resp = requests.get(search_url, params=params)
    data = resp.json()
    docs = [(doc["identifier"], doc["title"], doc["description"])
            for doc in data["response"]["docs"]]
    return docs

def choose(docs):
    """Print line number, title and truncated description for
    each tuple in :docs. Get the user to pick a line
    number. If it's valid, return the first item in the
    chosen tuple (the "identifier"). Otherwise, return None."""
    last = len(docs) - 1
    for num, doc in enumerate(docs):
        print(f"{num}: ({doc[1]}) {doc[2][:30]}...")
    index = input(f"Which would you like to see (0 to {last})? ")
    try:
        return docs[int(index)][0]
    except:
        return None

def display(identifier):
    """Display the Archive video with :identifier in the browser"""
    details_url = "https://archive.org/details/{}".format(identifier)
    print("Loading", details_url)
    webbrowser.open(details_url)

def main(title):
    """Find any movies that match :title.
       Get the user's choice and display it in the browser."""
    identifiers = search(title)
    if identifiers:
        identifier = choose(identifiers)
        if identifier:
            display(identifier)
        else:
            print("Nothing selected")
    else:
        print("Nothing found for", title)

if __name__ == "__main__":
    main(sys.argv[1])
  • 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.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.

四、测试用Web服务器

  • 使用python自带装备http.server
# 使用默认的8000端口
python -m http.server

# 指定端口8888
python -m http.server 8888
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

使用Ctrl + c退出。
测试

curl -s --head http://localhost:8000
curl -s -I http://localhost:8000
echo "" | telnet 127.0.0.1 8001
curl telnet://hostname:port
  • 1.
  • 2.
  • 3.
  • 4.
  • 使用bottle
    安装软件包
pip install bottle
  • 1.

配置脚本

from bottle import route, run

@route("/")
def home():
    return "http通的"

run(host="localhost", port=9999)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

启动并测试

python demo.py
curl http://localhost:9999
  • 1.
  • 2.

测试脚本

import requests

try:
    url = "https://www.sina.com"
    resp = requests.get(url)
    if resp.status_code == 200:
        if len(m := resp.text) < 20:
            print(m)
        else:
            print(f"Header: {resp.headers}\n")
            print(f"Content: {resp.text[:20]}...")

except requests.exceptions.ConnectionError:
    print("服务未启动")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

五、python的主流Web框架

  • Flask
    她在易用性和丰富性之间取得了平衡。
pip install flask
  • 1.
  • Django
    特别适合于大型站点。有内建数据库支持。

六、工具链的使用

1. pip

从Python3.4开始Python自带pip工具。
基本使用

pip install flask
pip uninstall flask

pip install flask==0.9.0
pip install 'flask>=0.9.0' # 避免将>解释为输出重定向

pip freeze > requirements.txt
pip install -r requirements.txt

pip install --upgrade pip
pip install --upgrade flas
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
2. pipenv

pipenv结合了pip和virtualenv的特性。

pip install pipenv
  • 1.

参考: https://blog.csdn.net/master_hunter/article/details/128198145

3. 源码安装

下载源码,解压zip或tar文件,在包含setup.py的目录中运行

python setup.py install
  • 1.
4. IPython

是python shell的增强版。

pip install ipython
  • 1.
5. 将python项目打包为whl文件

将 Python 项目(类或函数模块)代码打包成 .whl 文件(Wheel 文件)是为了方便在其他地方安装和使用你的 Python 应用程序或库。以下是逐步说明如何将 Python 代码打包成 .whl 文件:

# 步骤1:安装 wheel 模块
pip install wheel

# 步骤2:进入项目目录
cd xxx

# 步骤3:创建 setup.py 文件
# 在项目目录中创建一个名为 setup.py 的文件,并添加以下内容:
from setuptools import setup, find_packages

setup(
    name='your_project_name',
    version='1.0',
    packages=find_packages(),
)

# 将 your_project_name 替换为你的项目名称。

# 步骤4:构建 .whl 文件
# 在命令行中,进入项目目录,并运行以下命令来构建 .whl 文件:
python setup.py bdist_wheel

# 步骤5:查找 .whl 文件
# 构建成功后,你将在 dist 文件夹中找到生成的 .whl 文件,
# 其文件名格式为 <your_project_name>-<version>-py3-none-any.whl。

# 步骤6:安装 .whl 文件
pip install dist/your_project_name-1.0-py3-none-any.whl
  • 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.

还有一种方法是借助于build和pyproject.toml

可参考: https://blog.csdn.net/weixin_42439274/article/details/140437458

6. 如何将python项目打包为exe文件

要将Python项目打包为exe文件,并尽可能地减小包的体积,可以使用工具如PyInstaller或者cx_Freeze,小众的还有py2exe。

6.1 使用PyInstaller打包
# 安装软件包
pip install pyinstaller -i https://mirrors.aliyun.com/pypi/simple

# 打包为控制台程序——提供console控制台窗口。参数c可省略。
pyinstaller -Fc -i your_ico.ico your_script.py

# 打包不提供console控制台窗口
pyinstaller -Fw -i your_ico.ico your_script.py

# 借助生成的spec文件打包
# 参考:https://blog.csdn.net/qq_45956730/article/details/139992894
pyinstaller your_script.spec
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

PyInstaller会在项目目录中生成一个dist目录,在这个目录里你会找到打包好的EXE文件。
–onefile参数(-F)指示PyInstaller创建一个单一的可执行文件,如果你想要一个包含所有依赖的文件夹,可以省略这个参数。

6.2 Pyinstaller打包过程中要注意的问题
  • 打包文件路径中不能出现中文
  • 缺少导入hook文件
    有时即使打包成功了,在运行exe时候,还是会有报错并闪退。如果报错为:FileNotFoundError: [Errno 2] No such file or directory:……
    那是缺少hook文件,要在pyinstaller的安装路径里的hook增加一个自定义的hook。
    hook文件的命名规范为: hook-【库名】.py。
    例如以我在打包程序中用了结巴分词这个功能库为例,那我要建立一个hook-jieba.py,并写入:
from PyInstaller.utils.hooks import collect_data_files
datas = collect_data_files("jieba")
  • 1.
  • 2.

然后放到~\Lib\site-packages\PyInstaller\hooks中去,再次运行pyinstaller打包既可解决该问题。

  • 缺少导入功能库模块
    如果报错为 no moduler named “pandas._libs.skiplist”,那就要手动import库,解决方法打开生成的spec文件,找到 hiddenimports=[],加上要添加的库,将其改动如下,hiddenimports=[“pandas._libs.skiplist”],然后删除dist里面的exe文件,重新用spec文件打包,pyinstaller **.spec。即可解决该问题。
  • 解决生成的EXE体积过大的问题
    可以借助虚拟环境,在纯净的虚拟环境中按需安装依赖包,然后打包成EXE。主要就是减少无关包的安装——pyinstaller是将整个运行环境进行打包。

七、使用Nuitka将Python项目打包为EXE

Nuitka是将python源码转成C++(这里得到的是二进制的pyd文件),然后再编译成可执行文件。

可以参考: https://www.lixiaofei2yy.website/python的打包神器nuitka
安装包

pip install Nuitka
  • 1.

需要下载C++的编译器,比如‌Visual Studio 2022默认的C编译器,MinGW64或者clang
打包命令

nuitka --standalone --show-memory --show-progress --nofollow-imports --plugin-enable=qt-plugins --follow-import-to=utils,src --output-dir=out --windows-icon-from-ico=./logo.ico demo.py
  • 1.

参数及含义:

  • –standalone:方便移植到其他机器,不用再安装python
  • –show-memory --show-progress:展示整个安装的进度过程
  • –nofollow-imports:不编译代码中所有的import,比如keras,numpy之类的。
  • –plugin-enable=qt-plugins:我这里用到pyqt5来做界面的,这里nuitka有其对应的插件。
  • –follow-import-to=utils,src:需要编译成C++代码的指定的2个包含源码的文件夹,这里用,来进行分隔。
  • –output-dir=out:指定输出的结果路径为out。
  • –windows-icon-from-ico=./logo.ico:指定生成的exe的图标为logo.ico这个图标,这里推荐一个将图片转成ico格式文件的网站(比特虫)。
  • –windows-disable-console:运行exe取消弹框。这里没有放上去是因为我们还需要调试,可能哪里还有问题之类的。

依赖包不会被nuitka处理,还需要复制依赖包(Lib\site-packages\下)到发布目录demo.dist下(与exe文件同一目录)。