Python 相关 

Last Update: 2024-04-24

目录

Python pip 使用

pip 安装

一般来说 windows 上安装 python3 以后默认就带 pip 了。

linux 有些系统不预装 pip,需要 sudo apt install python3-pip 手动安装。

pip 换源

linux 下修改 ~/.pip/pip.conf (没有就创建一个),内容如下:

[global]
index-url = https://mirrors.aliyun.com/pypi/simple/

windows 下创建 C:\Users<user>\AppData\Roaming\pip\pip.ini 文件,内容如下

[global]
index-url = https://mirrors.aliyun.com/pypi/simple/

包管理

pip install <package-name> 安装包。

pip uninstall <package-name> 卸载包。

pip freeze > requirements.txt 依赖导出到 requirements.txt 文件。

pip install -r requirements.txt 根据 requirements.txt 安装依赖。

Python 3.x 在 Windows 上的多版本共存

基本配置

安装 Python 之后会顺带安装一个 python launcher。

C:\Program Files\python37 和 C:\Program Files\python38 是两个 Python 的安装目录。

执行 python -V 的输出取决于环境变量的顺序。

执行 py -3.7py -3.8 可以指定 Python 版本。

执行 py -3.7 -m 可以把 Python 的库模块当作脚本来执行,比如:

注意:

  1. 安装完 virtualenv 之后不能在 PowerShell 里面直接使用 virualenv 命令
  2. 想要直接使用命令需要添加环境变量 %USERPROFILE%\AppData\Roaming\Python\Python37\Scripts 到 Path
  3. 添加完环境变量后,virtualenv 基于的 Python 版本取决于 Python 安装目录在环境变量里的顺序

%USERPROFILE%\AppData\Roaming\Python\Python37\Scripts 和 %USERPROFILE%\AppData\Roaming\Python\Python37\Scripts 是 Python 包启动脚本的所在目录。

踩坑记录

PowerShell 默认不允许执行 .ps1 脚本文件

需要更改 PowerShell 的执行策略 Set-ExecutionPolicy RemoteSigned

Set-ExecutionPolicy <Policy><Policy> 的有效参数:

Python csv 文件读写

读取 csv 文件

import csv

with open('stock.csv','r') as fp:
    reader = csv.reader(fp)
    titles = next(reader)
    for x in reader:
        print(x)

这样操作,以后获取数据的时候,就要通过下表来获取数据。如果想要在获取数据的时候通过标题来获取,可以使用 DictReader。示例代码如下:

import csv

with open('stock.csv','r') as fp:
    reader = csv.DictReader(fp)
    for x in reader:
        print(x['turnoverVol'])

写入数据到 csv 文件

写入数据到csv文件,需要创建一个 writer 对象,主要用到两个方法。一个是 writerow 写入一行。一个是 writerows 写入多行。示例代码如下:

import csv

headers = ['name','age','classroom']
values = [
    ('zhiliao',18,'111'),
    ('wena',20,'222'),
    ('bbc',21,'111')]

with open('test.csv','w',newline='') as fp:
    writer = csv.writer(fp)
    writer.writerow(headers)
    writer.writerows(values)

使用 DictWriter 可以使用字典的方式把数据写进去。示例代码如下:

import csv

headers = ['name','age','classroom']
values = [
    {"name":'wenn',"age":20, "classroom":'222'},
    {"name":'abc' ,"age":30, "classroom":'333'}]

with open('test.csv','w',newline='') as fp:
    writer = csv.DictWriter(fp,headers)
    writer = csv.writeheader()
    writer.writerow({'name':'zhiliao',"age":18,"classroom":'111'})
    writer.writerows(values)

Python JSON 文件处理

JSON 支持数据格式

  1. 对象 (字典)。使用花括号。
  2. 数组 (列表)。使用方括号。
  3. 整形、浮点型、布尔类型还有null类型。
  4. 字符串类型 (字符串必须要用双引号,不能用单引号)。

多个数据之间使用逗号分开。

json 本质上就是一个字符串。

字典和列表转 JSON

import json

books = [{'title': '钢铁是怎样练成的','price': 9.8},
        {'title': '红楼梦','price': 9.9}]
json_str = json.dumps(books,ensure_ascii=False)
print(json_str)

json 包做 dump 操作的时候,只能处理 ascii 字符,因此会将中文进行转义,这时可以使用 ensure_ascii=False 关闭这个特性。

Python 中只有 int, float, str, list, dict, tuple 等基本数据类型才能转换成 JSON 格式的字符串。

直接 dump 到文件

json 模块中除了 dumps 函数,还有一个 dump 函数,这个函数可以传入一个文件指针,直接将字符串写入到文件中。示例代码如下:

books = [{'title': '钢铁是怎样练成的','price': 9.8},
        {'title': '红楼梦','price': 9.9}]
with open('a.json','w') as fp:
    json.dump(books,fp)

json 字符串转 Python 对象

json_str = '[{"title": "钢铁是怎样练成的", "price": 9.8}, {"title": "红楼梦", "price": 9.9}]'
books = json.loads(json_str,encoding='utf-8')
print(type(books))
print(books)

从文件中读取 json 字符串

import json

with open('a.json','r',encoding='utf-8') as fp:
    json_str = json.load(fp)
    print(json_str)

Python 对 requests 包配置代理

全局走 socks5 代理

import requests
import socket
import socks

socks.set_default_proxy(socks.SOCKS5, "192.168.50.101", 10808)
socket.socket = socks.socksocket
resp = requests.get(url="https://ifconfig.me/ip")
text = resp.content.decode('utf-8')
print(text)

http 请求走 socks5 代理

import requests

proxies = {
    "http": "socks5://192.168.50.101:10808",
    "https": "socks5://192.168.50.101:10808",
}
resp = requests.get(url="https://httpbin.org/ip", proxies=proxies)
text = resp.content.decode('utf-8')
print(text)

Python 与 PostgreSQL

连接到 PostgreSQL 的问题

首先执行 pip install psycopg2 安装驱动包。如果缺少 pg_config 文件会出现以下报错。

Error: pg_config executable not found.

pg_config is required to build psycopg2 from source.  Please add the directory
containing pg_config to the $PATH or specify the full executable path with the
option:

    python setup.py build_ext --pg-config /path/to/pg_config build ...

pg_configpostgresql-devel 这个包里,需要安装:

如果没有安装 gcc 也会报错:

...
unable to execute 'gcc': No such file or directory

It appears you are missing some prerequisite to build the package from source.

You may install a binary package by installing 'psycopg2-binary' from PyPI.
If you want to install psycopg2 from source, please install the packages
required for the build and try again.
...

sudo dnf install gcc 或者 sudo apt install gcc 安装 gcc 就好了。