python模块集合
# 装饰器
def performance_monitor(func):
def wrapper(*args, **kwargs):
import time
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"函数 {func.__name__} 执行耗时: {end_time - start_time}秒")
return result
return wrapper
@performance_monitor
def backup_database():
# 模拟数据库备份
import time
#下面填需要执行的操作
time.sleep(2)
print("数据库备份完成")
backup_database()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 并发编程
# 使用多线程处理复杂任务
from concurrent.futures import ThreadPoolExecutor
def process_server_log(log_file):
# 处理单个日志文件的复杂逻辑
pass
def batch_log_processing(log_files):
with ThreadPoolExecutor(max_workers=10) as executor:
executor.map(process_server_log, log_files)
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 网络编程
import socket
import requests
# socket编程
def port_scan(host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((host, port))
if result == 0:
print(f"Port {port} is open")
sock.close()
except Exception as e:
print(f"Error scanning port {port}: {e}")
# 发起HTTP请求监控服务
def check_service_health(url):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
print(f"Service {url} is healthy")
else:
print(f"Service {url} returned status code {response.status_code}")
except requests.RequestException as e:
print(f"Service {url} is down: {e}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 系统交互与自动化
import os
import subprocess
import shutil
# 文件和目录操作
def backup_directory(source, destination):
try:
shutil.copytree(source, destination)
print(f"Backup of {source} completed successfully")
except Exception as e:
print(f"Backup failed: {e}")
# 执行系统命令
def run_system_command(command):
try:
result = subprocess.run(command, shell=True, capture_output=True, text=True)
print("Command output:", result.stdout)
return result.stdout
except Exception as e:
print(f"Command execution failed: {e}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21


上次更新: 2025/05/14, 15:46:36