优秀的编程知识分享平台

网站首页 > 技术文章 正文

【python】常用的内置函数和包

nanyue 2025-03-05 19:41:37 技术文章 3 ℃

1.os- 操作系统接口

与操作系统交互:

import os
current_directory = os.getcwd()  # Get the current working directory

2.sys- 系统特定参数和函数

访问系统特定的参数和功能:

import sys
sys.exit()  # Exit the script

3.datetime- 基本日期和时间类型

与日期和时间一起工作:

from datetime import datetime
now = datetime.now()  # Current date and time

4.math- 数学函数

执行数学运算:

import math
result = math.sqrt(16)  # Square root

5.random- 生成伪随机数

生成伪随机数:

import random
number = random.randint(1, 10)  # Random integer between 1 and 10

6.json- JSON 编码器和解码器

解析和生成 JSON 数据:

import json
json_string = json.dumps({'name': 'Alice', 'age': 30})  # Dictionary to JSON string

7.re- 正则表达式

使用正则表达式:

import re
match = re.search('Hello', 'Hello, world!')  # Search for 'Hello' in the string

8.urllib- URL 处理模块

与 URL 一起工作:

from urllib.request import urlopen
content = urlopen('http://example.com').read()  # Fetch the content of a webpage

9.http- HTTP 模块

创建 HTTP 服务器和处理 HTTP 请求:

from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b'Python HTTP Server')
        self.wfile.write(b'

Hello from a simple Python HTTP server!

')def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler): server_address = ('', 8000) # Serve on all addresses, port 8000 httpd = server_class(server_address, handler_class) print("Server starting on port 8000...") httpd.serve_forever()if __name__ == '__main__': run()

10.子进程- 子进程管理

启动新进程并连接到它们的输入/输出/错误管道:

import subprocess
subprocess.run(['ls', '-l'])  # Run the 'ls -l' command

11.socket- 低级网络接口

创建网络客户端和服务器:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create a TCP/IP socket

12.threading- 基于线程的并行

管理代码的并发执行:

import threading
def worker():
    print("Worker thread executing")
thread = threading.Thread(target=worker)
thread.start()

13.多进程- 基于进程的并行

管理并发进程:

from multiprocessing import Process
def worker():
    print("Worker process")
p = Process(target=worker)
p.start()

14.argparse- 命令行选项、参数和子命令解析器

解析命令行参数:

import argparse
parser = argparse.ArgumentParser(description="Process some integers.")
args = parser.parse_args()

15.日志记录- 日志记录功能

记录消息(调试、信息、警告、错误和严重):

import logging
logging.warning('This is a warning message')

16.unittest- 单元测试框架

创建和运行单元测试:

import unittest
class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

17.pathlib- 面向对象的文件系统路径

以面向对象的方式处理文件系统路径:

from pathlib import Path
p = Path('.')

18.functools- 高阶函数和可调用对象操作

使用高阶函数和操作在可调用对象上:

from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

19.collections- 容器数据类型

使用专用容器数据类型(deque、Counter、OrderedDict 等):

from collections import Counter
c = Counter('hello world')

20.itertools- 创建迭代器的函数,用于高效循环

构建和使用迭代器以实现高效的循环:

import itertools
for combination in itertools.combinations('ABCD', 2):
    print(combination)

21.hashlib- 安全哈希和信息摘要算法

将数据哈希化:

import hashlib
hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.hexdigest()

22.csv- CSV 文件读取和写入

从 CSV 文件中读取和写入:

import csv
with open('file.csv', mode='r') as infile:
    reader = csv.reader(infile)

23.xml.etree.ElementTree- 元素树 XML API

解析和创建 XML 数据:

import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()

24.sqlite3- SQLite 数据库的 DB-API 2.0 接口

与 SQLite 数据库交互:

import sqlite3
conn = sqlite3.connect('example.db')

25.tkinter- 图形用户界面工具包

创建 GUI 应用程序:

import tkinter as tk
root = tk.Tk()

26.pickle- Python 对象序列化

将 Python 对象结构序列化和反序列化:

import pickle
serialized_obj = pickle.dumps(obj)

27.io- 处理流的核心工具

处理流(类似文件的对象):

from io import StringIO
f = StringIO("some initial text data")

28.时间- 时间访问和转换

访问时间相关功能:

import time
time.sleep(1)  # Sleep for 1 second

29.日历- 通用日历相关功能

与日历一起工作:

import calendar
print(calendar.month(2023, 1))  # Print the calendar for January 2023

30.队列- 一个同步队列类

管理队列,在多线程编程中很有用:

from queue import Queue
q = Queue()

31.shutil- 高级文件操作

执行高级文件操作,如复制和存档:

import shutil
shutil.copyfile('source.txt', 'dest.txt')

32.glob- Unix 风格路径名模式扩展

查找匹配指定模式的文件:

import glob
for file in glob.glob("*.txt"):
    print(file)

33.tempfile- 生成临时文件和目录

创建临时文件和目录:

import tempfile
temp = tempfile.TemporaryFile()

34.bz2- 支持 Bzip2 压缩

使用 bzip2 压缩和解压缩数据:

import bz2
compressed = bz2.compress(b'your data here')

35.gzip- 支持 Gzip 压缩

使用 gzip 压缩解压缩数据:

import gzip
with gzip.open('file.txt.gz', 'wt') as f:
    f.write('your data here')

36.ssl- 用于套接字对象的 TLS/SSL 包装

处理网络套接字的 TLS/SSL 加密和对方认证:

import ssl
ssl.wrap_socket(sock)

37.imaplib- IMAP4 协议客户端

访问和操作 IMAP4 邮件:

import imaplib
mail = imaplib.IMAP4_SSL('imap.example.com')

38.smtp 协议客户端

使用简单邮件传输协议(SMTP)发送邮件:

import smtplib
server = smtplib.SMTP('smtp.example.com', 587)

39.电子邮件- 管理电子邮件消息

管理电子邮件消息,包括 MIME 和其他基于 RFC 2822 的消息文档:

from email.message import EmailMessage
msg = EmailMessage()

40.base64- 基 16,基 32,基 64,基 85 数据编码

使用 Base64 编码和解码数据:

import base64
encoded_data = base64.b64encode(b'data to encode')

41.difflib- 计算差异的辅助工具

比较序列并生成可读的差异:

import difflib
diff = difflib.ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
                     'ore\ntree\nemu\n'.splitlines(keepends=True))
print(''.join(diff))

42.gettext- 多语言国际化服务

国际化您的 Python 程序:

import gettext
gettext.install('myapp')

43.locale- 国际化服务

访问特定文化数据格式的数据库:

import locale
locale.setlocale(locale.LC_ALL, '')

44.secrets- 生成用于管理秘密的安全随机数

生成用于管理秘密(如令牌或密码)的安全随机数:

import secrets
secure_token = secrets.token_hex(16)

45.uuid- 根据 RFC 4122 的 UUID 对象

生成全局唯一标识符(UUID):

import uuid
unique_id = uuid.uuid4()

46.html- 超文本标记语言支持

处理和操作 HTML 实体:

import html
escaped = html.escape('link')

47.ftplib- FTP 协议客户端

与 FTP 协议交互并传输文件:

from ftplib import FTP
ftp = FTP('ftp.example.com')

48.tarfile- 读取和写入 Tar 归档文件

与 tar 归档文件一起工作,允许您归档和压缩/解压缩:

import tarfile
with tarfile.open('sample.tar.gz', 'w:gz') as tar:
    tar.add('sample.txt')
最近发表
标签列表