1. 单元测试
import unittest
class FunctionTest(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
if __name__ == '__main__':
unittest.main()
2. 数据库备份
import os
import subprocess
def backup_mysql_database(host, user, password, database_name, backup_directory):
backup_filename = f"{database_name}_backup.sql"
backup_path = os.path.join(backup_directory, backup_filename)
command = f"mysqldump -h {host} -u {user} -p{password} {database_name} > {backup_path}"
try:
subprocess.run(command, shell=True, check=True)
print(f"Database {database_name} backed up successfully to {backup_path}")
except subprocess.CalledProcessError as e:
print(f"Error backing up database: {e}")
3. 日志分析
import re
def analyze_logs(log_file):
mac_pattern = r'([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})'
with open(log_file, 'r') as file:
for line in file:
match = re.search(mac_pattern, line)
if match:
print(match.group())
4. 文件压缩
import zipfile
def compress_files(file_paths, zip_file):
with zipfile.ZipFile(zip_file, 'w') as myzip:
for file_path in file_paths:
myzip.write(file_path)
compress_files(['file1.txt', 'file2.txt'], 'archive.zip')
5. 生成文档
from docx import Document
def generate_report(data, report_file):
doc = Document()
doc.add_heading('Report', 0)
for key, value in data.items():
doc.add_heading(key, 1)
doc.add_paragraph(str(value))
doc.save(report_file)
generate_report(data, 'my_report.docx')