最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

從基礎(chǔ)到高級(jí)應(yīng)用詳解Python網(wǎng)絡(luò)通信的完整指南

 更新時(shí)間:2026年05月13日 09:31:08   作者:IT策士  
Python在網(wǎng)絡(luò)編程領(lǐng)域展現(xiàn)出了強(qiáng)大的versatility和效率,從底層的套接字編程到高級(jí)的異步框架,Python提供了豐富的工具和庫(kù)來(lái)滿足各種網(wǎng)絡(luò)通信需求,通過(guò)本文我們不僅可以掌握基礎(chǔ)的TCP/UDP通信,還能學(xué)習(xí)HTTP、WebSocket等協(xié)議的應(yīng)用,感興趣的小伙伴可以了解下

1. 引言

在當(dāng)今互聯(lián)網(wǎng)時(shí)代,網(wǎng)絡(luò)通信已經(jīng)成為現(xiàn)代軟件開(kāi)發(fā)中不可或缺的一部分。Python作為一種versatile編程語(yǔ)言,提供了豐富的網(wǎng)絡(luò)編程庫(kù)和工具,使得開(kāi)發(fā)者能夠輕松地構(gòu)建各種網(wǎng)絡(luò)應(yīng)用。本文將深入探討Python網(wǎng)絡(luò)通信的方方面面,從基礎(chǔ)的套接字編程到高級(jí)的異步網(wǎng)絡(luò)框架,幫助您全面掌握Python網(wǎng)絡(luò)編程技能。

2. 網(wǎng)絡(luò)基礎(chǔ)知識(shí)

在深入Python網(wǎng)絡(luò)編程之前,我們需要先了解一些基本的網(wǎng)絡(luò)概念。

2.1 OSI模型

OSI(Open Systems Interconnection)模型是一個(gè)用于理解網(wǎng)絡(luò)通信的概念性框架,它包含7層:

  1. 物理層
  2. 數(shù)據(jù)鏈路層
  3. 網(wǎng)絡(luò)層
  4. 傳輸層
  5. 會(huì)話層
  6. 表示層
  7. 應(yīng)用層

Python網(wǎng)絡(luò)編程主要關(guān)注上層(傳輸層及以上)。

2.2 TCP/IP協(xié)議族

TCP/IP是互聯(lián)網(wǎng)的基礎(chǔ)協(xié)議族,包括:

  • IP(Internet Protocol):負(fù)責(zé)數(shù)據(jù)包的尋址和路由
  • TCP(Transmission Control Protocol):提供可靠的、面向連接的數(shù)據(jù)傳輸
  • UDP(User Datagram Protocol):提供不可靠的、無(wú)連接的數(shù)據(jù)傳輸

2.3 端口號(hào)

端口號(hào)是用于區(qū)分同一臺(tái)計(jì)算機(jī)上不同網(wǎng)絡(luò)服務(wù)的數(shù)字標(biāo)識(shí)符,范圍從0到65535。

3. Python套接字編程

套接字(Socket)是網(wǎng)絡(luò)編程的基礎(chǔ),它提供了一種跨網(wǎng)絡(luò)通信的端點(diǎn)。

3.1 創(chuàng)建TCP套接字

以下是一個(gè)簡(jiǎn)單的TCP服務(wù)器和客戶端示例:

服務(wù)器端代碼:

import socket

def start_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('localhost', 12345))
    server_socket.listen(1)
    print("Server is listening on port 12345")

    while True:
        client_socket, address = server_socket.accept()
        print(f"Connection from {address} has been established!")
        client_socket.send(bytes("Welcome to the server!", "utf-8"))
        client_socket.close()

if __name__ == "__main__":
    start_server()

客戶端代碼:

import socket

def connect_to_server():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect(('localhost', 12345))
    message = client_socket.recv(1024)
    print(message.decode("utf-8"))
    client_socket.close()

if __name__ == "__main__":
    connect_to_server()

3.2 創(chuàng)建UDP套接字

UDP通信不需要建立連接,這里是一個(gè)簡(jiǎn)單的UDP服務(wù)器和客戶端示例:

服務(wù)器端代碼:

import socket

def start_udp_server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_socket.bind(('localhost', 12345))
    print("UDP server is listening on port 12345")

    while True:
        message, address = server_socket.recvfrom(1024)
        print(f"Message from {address}: {message.decode('utf-8')}")
        server_socket.sendto(b"Message received", address)

if __name__ == "__main__":
    start_udp_server()

客戶端代碼:

import socket

def send_udp_message():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    client_socket.sendto(b"Hello, UDP Server!", ('localhost', 12345))
    response, _ = client_socket.recvfrom(1024)
    print(f"Response from server: {response.decode('utf-8')}")
    client_socket.close()

if __name__ == "__main__":
    send_udp_message()

4. HTTP通信

HTTP是應(yīng)用層協(xié)議,廣泛用于Web應(yīng)用。Python提供了多種方式來(lái)處理HTTP通信。

4.1 使用requests庫(kù)

requests庫(kù)是Python中最流行的HTTP客戶端庫(kù)之一。

安裝:

pip install requests

使用示例:

import requests

def get_example():
    response = requests.get('https://api.github.com/events')
    print(response.status_code)
    print(response.json())

def post_example():
    data = {'key': 'value'}
    response = requests.post('https://httpbin.org/post', data=data)
    print(response.text)

if __name__ == "__main__":
    get_example()
    post_example()

4.2 使用http.server模塊

Python的標(biāo)準(zhǔn)庫(kù)提供了http.server模塊,可以快速創(chuàng)建一個(gè)簡(jiǎn)單的HTTP服務(wù)器:

from http.server import HTTPServer, SimpleHTTPRequestHandler
import socketserver

def run_server(port=8000):
    handler = SimpleHTTPRequestHandler
    with socketserver.TCPServer(("", port), handler) as httpd:
        print(f"Serving at port {port}")
        httpd.serve_forever()

if __name__ == "__main__":
    run_server()

這個(gè)服務(wù)器將serve當(dāng)前目錄下的文件。

5. 異步網(wǎng)絡(luò)編程

異步編程允許同時(shí)處理多個(gè)網(wǎng)絡(luò)連接,提高程序的效率。

5.1 使用asyncio

asyncio是Python的異步編程標(biāo)準(zhǔn)庫(kù)。

異步HTTP客戶端示例:

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://python.org')
        print(html[:100])

if __name__ == "__main__":
    asyncio.run(main())

異步HTTP服務(wù)器示例:

from aiohttp import web

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = f"Hello, {name}!"
    return web.Response(text=text)

app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/{name}', handle)])

if __name__ == '__main__':
    web.run_app(app)

6. 網(wǎng)絡(luò)協(xié)議實(shí)現(xiàn)

Python可以用來(lái)實(shí)現(xiàn)各種網(wǎng)絡(luò)協(xié)議。這里我們以SMTP(Simple Mail Transfer Protocol)為例。

6.1 使用smtplib發(fā)送郵件

import smtplib
from email.mime.text import MIMEText
from email.header import Header

def send_email():
    sender = 'from@example.com'
    receivers = ['to@example.com']

    message = MIMEText('Python 郵件發(fā)送測(cè)試...', 'plain', 'utf-8')
    message['From'] = Header("菜鳥(niǎo)教程", 'utf-8')
    message['To'] =  Header("測(cè)試", 'utf-8')
    
    subject = 'Python SMTP 郵件測(cè)試'
    message['Subject'] = Header(subject, 'utf-8')
    
    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("郵件發(fā)送成功")
    except smtplib.SMTPException:
        print("Error: 無(wú)法發(fā)送郵件")

if __name__ == "__main__":
    send_email()

7. 網(wǎng)絡(luò)安全

在進(jìn)行網(wǎng)絡(luò)編程時(shí),安全性是一個(gè)重要的考慮因素。

7.1 使用SSL/TLS

Python的ssl模塊提供了對(duì)SSL/TLS的支持。以下是一個(gè)使用SSL的TCP客戶端示例:

import ssl
import socket

def ssl_client():
    context = ssl.create_default_context()
    with socket.create_connection(('www.python.org', 443)) as sock:
        with context.wrap_socket(sock, server_hostname='www.python.org') as secure_sock:
            print(f"Connected to {secure_sock.version()}")
            secure_sock.send(b"GET / HTTP/1.1\r\nHost: www.python.org\r\n\r\n")
            print(secure_sock.recv(1024))

if __name__ == "__main__":
    ssl_client()

7.2 處理網(wǎng)絡(luò)攻擊

在網(wǎng)絡(luò)編程中,我們需要注意防范各種攻擊,如DDoS攻擊、SQL注入等。以下是一個(gè)簡(jiǎn)單的IP黑名單實(shí)現(xiàn):

import socket
from collections import defaultdict

class IPBlocker:
    def __init__(self, max_attempts=5):
        self.ip_attempts = defaultdict(int)
        self.max_attempts = max_attempts

    def check_ip(self, ip):
        if self.ip_attempts[ip] >= self.max_attempts:
            return False
        self.ip_attempts[ip] += 1
        return True

def start_server():
    blocker = IPBlocker()
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('localhost', 12345))
    server_socket.listen(1)
    print("Server is listening on port 12345")

    while True:
        client_socket, address = server_socket.accept()
        ip = address[0]
        if blocker.check_ip(ip):
            print(f"Connection from {address} has been established!")
            client_socket.send(bytes("Welcome to the server!", "utf-8"))
        else:
            print(f"Connection from {address} has been blocked!")
            client_socket.send(bytes("You have been blocked due to too many attempts.", "utf-8"))
        client_socket.close()

if __name__ == "__main__":
    start_server()

8. 高級(jí)網(wǎng)絡(luò)編程技巧

8.1 使用Twisted框架

Twisted是一個(gè)事件驅(qū)動(dòng)的網(wǎng)絡(luò)編程框架,適用于開(kāi)發(fā)復(fù)雜的網(wǎng)絡(luò)應(yīng)用。

安裝Twisted:

pip install twisted

一個(gè)簡(jiǎn)單的Twisted echo服務(wù)器:

from twisted.internet import protocol, reactor, endpoints

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        self.transport.write(data)

class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()

endpoints.serverFromString(reactor, "tcp:1234").listen(EchoFactory())
reactor.run()

8.2 使用gevent進(jìn)行協(xié)程編程

gevent是一個(gè)基于協(xié)程的Python網(wǎng)絡(luò)庫(kù),它使用greenlet來(lái)提供高級(jí)同步API。

安裝gevent:

pip install gevent

使用gevent實(shí)現(xiàn)并發(fā)下載:

import gevent
from gevent import monkey
monkey.patch_all()  # 修補(bǔ)所有可能的阻塞
import requests

def download(url):
    print(f'Downloading {url}')
    response = requests.get(url)
    print(f'Downloaded {len(response.content)} bytes from {url}')

urls = [
    'https://www.python.org/',
    'https://www.yahoo.com/',
    'https://www.github.com/',
]

jobs = [gevent.spawn(download, url) for url in urls]
gevent.joinall(jobs)

9. 網(wǎng)絡(luò)監(jiān)控和分析

Python也可以用于網(wǎng)絡(luò)監(jiān)控和分析。

9.1 使用scapy進(jìn)行網(wǎng)絡(luò)嗅探

scapy是一個(gè)強(qiáng)大的交互式數(shù)據(jù)包操作程序和庫(kù)。

安裝scapy:

pip install scapy

一個(gè)簡(jiǎn)單的數(shù)據(jù)包嗅探器:

from scapy.all import *

def packet_callback(packet):
    if packet[TCP].payload:
        mypacket = str(packet[TCP].payload)
        if 'user' in mypacket.lower() or 'pass' in mypacket.lower():
            print(f"[*] Destination: {packet[IP].dst}")
            print(f"[*] {str(packet[TCP].payload)}")

sniff(filter="tcp port 110 or tcp port 25 or tcp port 143", prn=packet_callback, store=0)

注意:使用網(wǎng)絡(luò)嗅探工具時(shí),請(qǐng)確保你有合法權(quán)限。

9.2 使用psutil監(jiān)控網(wǎng)絡(luò)連接

psutil是一個(gè)跨平臺(tái)庫(kù),用于獲取運(yùn)行進(jìn)程和系統(tǒng)利用率(CPU、內(nèi)存、磁盤(pán)、網(wǎng)絡(luò)等)的信息。

安裝psutil:

pip install psutil

監(jiān)控網(wǎng)絡(luò)連接:

import psutil

def monitor_connections():
    for conn in psutil.net_connections():
        print(f"Local address: {conn.laddr}")
        print(f"Remote address: {conn.raddr}")
        print(f"Status: {conn.status}")
        print("---")

if __name__ == "__main__":
    monitor_connections()

10. 網(wǎng)絡(luò)應(yīng)用實(shí)例

讓我們通過(guò)一個(gè)更復(fù)雜的例子來(lái)綜合運(yùn)用我們學(xué)到的知識(shí)。我們將創(chuàng)建一個(gè)簡(jiǎn)單的聊天 服務(wù)器和客戶端。

10.1 聊天 服務(wù)器

import asyncio
import websockets
import json

class ChatServer:
    def __init__(self):
        self.clients = set()

    async def register(self, ws):
        self.clients.add(ws)
        print(f"New client connected. Total clients: {len(self.clients)}")

    async def unregister(self, ws):
        self.clients.remove(ws)
        print(f"Client disconnected. Total clients: {len(self.clients)}")

    async def broadcast(self, message):
        if self.clients:
            await asyncio.wait([client.send(message) for client in self.clients])

    async def ws_handler(self, websocket, path):
        await self.register(websocket)
        try:
            async for message in websocket:
                data = json.loads(message)
                await self.broadcast(json.dumps({"type": "message", "user": data['user'], "message": data['message']}))
        finally:
            await self.unregister(websocket)

server = ChatServer()

start_server = websockets.serve(server.ws_handler, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

10.2 聊天客戶端

import asyncio
import websockets
import json
import aioconsole

async def receive_messages(websocket):
    while True:
        try:
            message = await websocket.recv()
            data = json.loads(message)
            print(f"\n{data['user']}: {data['message']}")
        except websockets.exceptions.ConnectionClosed:
            print("Connection to server closed")
            break

async def send_messages(websocket, username):
    while True:
        message = await aioconsole.ainput()
        await websocket.send(json.dumps({"user": username, "message": message}))

async def chat_client():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        username = input("Enter your username: ")
        print(f"Connected to chat server as {username}")
        
        receive_task = asyncio.create_task(receive_messages(websocket))
        send_task = asyncio.create_task(send_messages(websocket, username))
        
        await asyncio.gather(receive_task, send_task)

asyncio.get_event_loop().run_until_complete(chat_client())

這個(gè)聊天應(yīng)用展示了如何使用WebSocket進(jìn)行實(shí)時(shí)雙向通信,以及如何使用asyncio處理并發(fā)操作。

11. 網(wǎng)絡(luò)性能優(yōu)化

在開(kāi)發(fā)網(wǎng)絡(luò)應(yīng)用時(shí),性能優(yōu)化是一個(gè)重要的考慮因素。以下是一些優(yōu)化技巧:

11.1 使用連接池

對(duì)于頻繁創(chuàng)建和關(guān)閉連接的應(yīng)用,使用連接池可以顯著提高性能。以下是使用aiohttp的連接池示例:

import asyncio
import aiohttp

async def fetch_url(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = ['http://example.com', 'http://example.org', 'http://example.net'] * 100
    
    connector = aiohttp.TCPConnector(limit=20)  # 限制并發(fā)連接數(shù)
    async with aiohttp.ClientSession(connector=connector) as session:
        tasks = [fetch_url(session, url) for url in urls]
        responses = await asyncio.gather(*tasks)
    
    print(f"Fetched {len(responses)} URLs")

asyncio.run(main())

11.2 使用緩存

對(duì)于頻繁訪問(wèn)的數(shù)據(jù),使用緩存可以減少網(wǎng)絡(luò)請(qǐng)求,提高響應(yīng)速度。以下是一個(gè)使用functools.lru_cache的簡(jiǎn)單緩存示例:

import requests
from functools import lru_cache

@lru_cache(maxsize=100)
def fetch_url(url):
    response = requests.get(url)
    return response.text

# 使用緩存的函數(shù)
print(fetch_url('http://example.com'))
print(fetch_url('http://example.com'))  # 這次會(huì)從緩存中獲取

11.3 壓縮數(shù)據(jù)

在網(wǎng)絡(luò)傳輸中,壓縮數(shù)據(jù)可以減少帶寬使用并提高傳輸速度。以下是一個(gè)使用gzip壓縮的示例:

import gzip
import requests

def send_compressed_data(url, data):
    compressed_data = gzip.compress(data.encode('utf-8'))
    headers = {'Content-Encoding': 'gzip'}
    response = requests.post(url, data=compressed_data, headers=headers)
    return response

# 使用壓縮發(fā)送數(shù)據(jù)
response = send_compressed_data('http://example.com/api', 'Large amount of data...')
print(response.status_code)

12. 網(wǎng)絡(luò)安全進(jìn)階

12.1 實(shí)現(xiàn)簡(jiǎn)單的加密通信

使用Python的cryptography庫(kù)實(shí)現(xiàn)加密通信:

from cryptography.fernet import Fernet

def generate_key():
    return Fernet.generate_key()

def encrypt_message(message, key):
    f = Fernet(key)
    return f.encrypt(message.encode())

def decrypt_message(encrypted_message, key):
    f = Fernet(key)
    return f.decrypt(encrypted_message).decode()

# 使用示例
key = generate_key()
message = "Hello, secure world!"
encrypted = encrypt_message(message, key)
decrypted = decrypt_message(encrypted, key)

print(f"Original: {message}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")

12.2 實(shí)現(xiàn)簡(jiǎn)單的身份驗(yàn)證

使用JWT(JSON Web Tokens)實(shí)現(xiàn)簡(jiǎn)單的身份驗(yàn)證:

import jwt
import datetime

SECRET_KEY = 'your-secret-key'

def generate_token(username):
    payload = {
        'username': username,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    }
    return jwt.encode(payload, SECRET_KEY, algorithm='HS256')

def verify_token(token):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        return payload['username']
    except jwt.ExpiredSignatureError:
        return 'Token expired'
    except jwt.InvalidTokenError:
        return 'Invalid token'

# 使用示例
token = generate_token('user123')
print(f"Generated token: {token}")
print(f"Verified username: {verify_token(token)}")

13. 分布式系統(tǒng)和微服務(wù)

Python也可以用于構(gòu)建分布式系統(tǒng)和微服務(wù)架構(gòu)。

13.1 使用gRPC進(jìn)行服務(wù)間通信

gRPC是一個(gè)高性能、開(kāi)源和通用的RPC框架。以下是一個(gè)簡(jiǎn)單的gRPC服務(wù)器和客戶端示例:

服務(wù)器:

import grpc
from concurrent import futures
import time
import hello_pb2
import hello_pb2_grpc

class Greeter(hello_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return hello_pb2.HelloReply(message=f"Hello, {request.name}!")

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(86400)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()

客戶端:

import grpc
import hello_pb2
import hello_pb2_grpc

def run():
    with grpc.insecure_channel('localhost:50051') as channel:
        stub = hello_pb2_grpc.GreeterStub(channel)
        response = stub.SayHello(hello_pb2.HelloRequest(name='World'))
    print("Greeter client received: " + response.message)

if __name__ == '__main__':
    run()

13.2 使用Celery進(jìn)行任務(wù)隊(duì)列

Celery是一個(gè)分布式任務(wù)隊(duì)列,可以用于處理大量消息。以下是一個(gè)簡(jiǎn)單的Celery任務(wù)示例:

from celery import Celery

app = Celery('tasks', broker='redis://localhost:6379')

@app.task
def add(x, y):
    return x + y

# 在另一個(gè)Python文件中使用這個(gè)任務(wù)
from tasks import add
result = add.delay(4, 4)
print(result.get())  # 輸出: 8

14. 網(wǎng)絡(luò)監(jiān)控和日志分析

14.1 使用ELK棧進(jìn)行日志分析

ELK棧(Elasticsearch, Logstash, Kibana)是一個(gè)強(qiáng)大的日志管理和分析工具集。以下是一個(gè)使用Python將日志發(fā)送到ELK棧的示例:

import logging
from cmreslogging.handlers import CMRESHandler

handler = CMRESHandler(hosts=[{'host': 'localhost', 'port': 9200}],
                       auth_type=CMRESHandler.AuthType.NO_AUTH,
                       es_index_name="my_python_index")

logger = logging.getLogger("python-logger")
logger.setLevel(logging.INFO)
logger.addHandler(handler)

# 使用logger
logger.info("This is a test log message")

14.2 網(wǎng)絡(luò)流量分析

使用pyshark庫(kù)進(jìn)行網(wǎng)絡(luò)流量分析:

import pyshark

def analyze_traffic(interface):
    capture = pyshark.LiveCapture(interface=interface)
    for packet in capture.sniff_continuously(packet_count=10):
        try:
            print(f"Source IP: {packet.ip.src}")
            print(f"Destination IP: {packet.ip.dst}")
            print(f"Protocol: {packet.transport_layer}")
            print("---")
        except AttributeError:
            pass

analyze_traffic('eth0')  # 替換為你的網(wǎng)絡(luò)接口名稱

15. 結(jié)語(yǔ)

Python在網(wǎng)絡(luò)編程領(lǐng)域展現(xiàn)出了強(qiáng)大的versatility和效率。從底層的套接字編程到高級(jí)的異步框架,Python提供了豐富的工具和庫(kù)來(lái)滿足各種網(wǎng)絡(luò)通信需求。通過(guò)本文的深入探討,我們不僅掌握了基礎(chǔ)的TCP/UDP通信,還學(xué)習(xí)了HTTP、WebSocket等協(xié)議的應(yīng)用,以及異步編程、安全性和性能優(yōu)化等高級(jí)主題。Python的簡(jiǎn)潔語(yǔ)法和強(qiáng)大的生態(tài)系統(tǒng)使得開(kāi)發(fā)者能夠快速構(gòu)建從簡(jiǎn)單的網(wǎng)絡(luò)應(yīng)用到復(fù)雜的分布式系統(tǒng)。隨著物聯(lián)網(wǎng)和云計(jì)算的發(fā)展,Python的網(wǎng)絡(luò)編程能力將在未來(lái)發(fā)揮更加重要的作用。

以上就是從基礎(chǔ)到高級(jí)應(yīng)用詳解Python網(wǎng)絡(luò)通信的完整指南的詳細(xì)內(nèi)容,更多關(guān)于Python網(wǎng)絡(luò)通信的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python 使用dict實(shí)現(xiàn)switch的操作

    Python 使用dict實(shí)現(xiàn)switch的操作

    這篇文章主要介紹了Python 使用dict實(shí)現(xiàn)switch的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-04-04
  • 老生常談Python startswith()函數(shù)與endswith函數(shù)

    老生常談Python startswith()函數(shù)與endswith函數(shù)

    下面小編就為大家?guī)?lái)一篇老生常談Python startswith()函數(shù)與endswith函數(shù)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-09-09
  • 在Pytorch中使用樣本權(quán)重(sample_weight)的正確方法

    在Pytorch中使用樣本權(quán)重(sample_weight)的正確方法

    今天小編就為大家分享一篇在Pytorch中使用樣本權(quán)重(sample_weight)的正確方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-08-08
  • Python讀取stdin方法實(shí)例

    Python讀取stdin方法實(shí)例

    在本篇文章中小編給大家分享了關(guān)于Python里如何讀取stdin的知識(shí)點(diǎn)以及相關(guān)實(shí)例內(nèi)容,需要的朋友們學(xué)習(xí)參考下。
    2019-05-05
  • python-pymongo常用查詢方法含聚合問(wèn)題

    python-pymongo常用查詢方法含聚合問(wèn)題

    這篇文章主要介紹了python-pymongo常用查詢方法含聚合問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • 在Python中實(shí)現(xiàn)隨機(jī)睡眠的方法示例

    在Python中實(shí)現(xiàn)隨機(jī)睡眠的方法示例

    在編寫(xiě)Python程序時(shí),有時(shí)我們需要讓程序暫停執(zhí)行一段時(shí)間,這種需求在爬蟲(chóng)、任務(wù)調(diào)度、API調(diào)用等場(chǎng)景中非常常見(jiàn),Python提供了time.sleep()函數(shù)來(lái)實(shí)現(xiàn)程序的暫停,但如果我們希望暫停的時(shí)間是隨機(jī)的,本文將詳細(xì)介紹如何在Python中實(shí)現(xiàn)隨機(jī)睡眠,并探討其應(yīng)用場(chǎng)景和進(jìn)階用法
    2025-01-01
  • pyecharts結(jié)合flask框架的使用

    pyecharts結(jié)合flask框架的使用

    這篇文章主要介紹了pyecharts結(jié)合flask框架,主要是介紹如何在Flask框架中使用pyecharts,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06
  • 深入理解python中實(shí)例方法的第一個(gè)參數(shù)self

    深入理解python中實(shí)例方法的第一個(gè)參數(shù)self

    在Python中,self?是類的實(shí)例方法的一個(gè)參數(shù),代表類的實(shí)例對(duì)象本身,在本篇文章中,我們將深入探討?self?的工作原理以及它在Python編程中的重要性,需要的可以參考下
    2023-09-09
  • 詳解Python使用OpenCV如何確定一個(gè)對(duì)象的方向

    詳解Python使用OpenCV如何確定一個(gè)對(duì)象的方向

    在本教程中,我們將構(gòu)建一個(gè)程序,該程序可以使用流行的計(jì)算機(jī)視覺(jué)庫(kù) OpenCV 確定對(duì)象的方向(即以度為單位的旋轉(zhuǎn)角度),感興趣的小伙伴可以了解一下
    2022-10-10
  • Pytorch模型轉(zhuǎn)onnx模型實(shí)例

    Pytorch模型轉(zhuǎn)onnx模型實(shí)例

    今天小編就為大家分享一篇Pytorch模型轉(zhuǎn)onnx模型實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-01-01

最新評(píng)論

夏邑县| 维西| 乌海市| 广平县| 女性| 涞源县| 张家川| 邯郸县| 沙雅县| 五华县| 淮滨县| 浑源县| 甘谷县| 南华县| 阿克陶县| 东乡族自治县| 霍山县| 社旗县| 原平市| 奉节县| 武汉市| 乌苏市| 汕尾市| 宁夏| 鲁甸县| 通江县| 冷水江市| 梨树县| 贡觉县| 东乡| 将乐县| 腾冲县| 镇原县| 平果县| 陵水| 慈溪市| 饶平县| 阿图什市| 海门市| 岗巴县| 鄱阳县|