NipGeihou's blog NipGeihou's blog
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档

NipGeihou

我见青山多妩媚,料青山见我应如是
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档
  • 教程

    • 安装
    • 流程控制与定义函数
    • 数据结构(类型)
    • 模块
    • 输入与输出
    • 错误与异常
    • 类
    • 标准库
      • 操作系统接口
        • os
        • dir()
        • help()
        • shutil - 文件管理
      • 文件通配符
      • 命令行参数
      • 字符串模式匹配
        • 正则匹配
        • 文本替换
      • 数学
        • 数学函数
        • 随机选择
        • 统计
      • 日期和时间
      • 数据压缩
      • 多线程
      • 日志记录
      • 用于操作列表的工具
        • array
        • collections 队列
        • bisect 有序列表
        • heapq 堆
      • 十进制浮点运算
        • decimal
      • 网络请求
        • requests
    • 虚拟环境和包
    • 开发环境
    • ORM - SQLAlchemy
  • Python
  • 教程
NipGeihou
2024-10-11
目录

标准库

# 操作系统接口

# os

import os
>>> os.getcwd()      # 返回当前工作目录
'C:\\Python313'
>>> os.chdir('/server/accesslogs')   # 改变当前工作目录
>>> os.system('mkdir today')   # 在系统 shell 中运行 mkdir 命令
0

# 读取环境变量
MONGODB_USERNAME = os.getenv("MONGODB_USERNAME")
database_url = os.environ.get("DATABASE_URL", "localhost:5432") # 不存在时返回参数2



一定要使用 import os 而不是 from os import * 。这将避免内建的 open() (opens new window) 函数被 os.open() (opens new window) 隐式替换掉,因为它们的使用方式大不相同。

# dir()

# help()

>>> import os
>>> dir(os)
<返回由模块的所有函数组成的列表>
>>> help(os)
<返回根据模块文档字符串创建的详细说明页面>

# shutil - 文件管理

>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'

# 文件通配符

使用通配符搜索创建文件列表

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

# 命令行参数

# 文件 demo.py
import sys
print(sys.argv) # 获取命令参数

以下是在命令行中运行 python demo.py one two three 输出的结果:

['demo.py', 'one', 'two', 'three']

# 字符串模式匹配

# 正则匹配

>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

# 文本替换

>>> 'tea for too'.replace('too', 'two')
'tea for two'

# 数学

# 数学函数

>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0

# 随机选择

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # 无替代的取样
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # [0.0, 1.0) 区间的随机浮点数
0.17970987693706186
>>> random.randrange(6)    # 从 range(6) 中随机选取的整数
4

# 统计

>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data) # 均值
1.6071428571428572
>>> statistics.median(data) # 中位数
1.25
>>> statistics.variance(data) # 方差
1.3720238095238095

# 日期和时间

>>> # 方便地构造和格式化日期值
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # 日期值支持日历运算
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368

# 数据压缩

>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

# 多线程

import threading, zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Finished background zip of:', self.infile)

background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')

background.join()    # 等待背景任务结束
print('Main program waited until background was done.')

# 日志记录

import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')

# 用于操作列表的工具

# array

array (opens new window) 模块提供了一种 array (opens new window) 对象,它类似于列表,但只能存储类型一致的数据且存储密度更高。 下面的例子显示了一个由存储为双字节无符号整数的数字 (类型码 "H" ) 组成的元组,而不是常规 Python int 对象列表所采用的每个条目 16 字节:

>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])

# collections 队列

collections (opens new window) 模块提供了一种 deque (opens new window) 对象,它类似于列表,但从左端添加和弹出的速度较快而在中间查找的速度较慢。 此种对象适用于实现队列和广度优先树搜索:

>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
    node = unsearched.popleft()
    for m in gen_moves(node):
        if is_goal(m):
            return m
        unsearched.append(m)

# bisect 有序列表

类似 zset

>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

# heapq 堆

>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data)                      # 将列表重新调整为堆顺序
>>> heappush(data, -5)                 # 添加一个新条目
>>> [heappop(data) for i in range(3)]  # 获取三个最小的条目
[-5, 0, 1]

# 十进制浮点运算

# decimal

>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73

# 网络请求

# requests

# 导入 requests 包
import requests

# 请求
resp = requests.get('https://www.runoob.com/')

# 响应
response.status_code // 状态码,通常200

resp.text() // 字符串文本

data = resp.json() // 返回json结构的字典or列表
print(data['data'])

上次更新: 2024/10/27, 22:58:29
类
虚拟环境和包

← 类 虚拟环境和包→

最近更新
01
iSCSI服务搭建
05-10
02
磁盘管理与文件系统
05-02
03
网络测试 - iperf3
05-02
更多文章>
Theme by Vdoing | Copyright © 2018-2025 NipGeihou | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式