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

360影视 2025-02-08 08:37 2

摘要:import rematch = re.search('Hello', 'Hello, world!') # Search for 'Hello' in the string

与操作系统交互:

import oscurrent_directory = os.getcwd # Get the current working directory

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

import syssys.exit # Exit the script

与日期和时间一起工作:

from datetime import datetimenow = datetime.now # Current date and time

执行数学运算:

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

生成伪随机数:

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

解析和生成 JSON 数据:

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

使用正则表达式:

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

与 URL 一起工作:

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

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

from http.server import HTTPServer, BaseHTTPRequestHandlerclass 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_foreverif __name__ == '__main__': run

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

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

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

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

管理代码的并发执行:

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

管理并发进程:

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

解析命令行参数:

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

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

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

创建和运行单元测试:

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

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

from pathlib import Pathp = Path('.')

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

from functools import lru_cache@lru_cache(maxsize=None)def fib(n): if n

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

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

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

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

将数据哈希化:

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

从 CSV 文件中读取和写入:

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

解析和创建 XML 数据:

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

与 SQLite 数据库交互:

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

创建 GUI 应用程序:

import tkinter as tkroot = tk.Tk

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

import pickleserialized_obj = pickle.dumps(obj)

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

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

访问时间相关功能:

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

与日历一起工作:

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

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

from queue import Queueq = Queue

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

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

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

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

创建临时文件和目录:

import tempfiletemp = tempfile.TemporaryFile

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

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

使用 gzip 压缩解压缩数据:

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

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

import sslssl.wrap_socket(sock)

访问和操作 IMAP4 邮件:

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

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

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

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

from email.message import EmailMessagemsg = EmailMessageimport base64encoded_data = base64.b64encode(b'data to encode')

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

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

国际化您的 Python 程序:

import gettextgettext.install('myapp')

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

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

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

import secretssecure_token = secrets.token_hex(16)

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

import uuidunique_id = uuid.uuid4

处理和操作 HTML 实体:

import htmlescaped = html.escape('link')

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

from FTPlib import FTPftp = FTP('ftp.example.com')import tarfilewith tarfile.open('sample.tar.gz', 'w:gz') as tar: tar.add('sample.txt')

来源:自由坦荡的湖泊AI

相关推荐