1. 文件操作:自动备份文件
场景:每日自动备份重要文件到指定目录。
import shutil
import datetime
def backup_file(src, dst_folder):
now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
dst_path = f"{dst_folder}/backup_{now}_{src.split('/')[-1]}"
shutil.copy2(src, dst_path)
print(f"Backup created at {dst_path}")
# 示例用法
backup_file("/path/to/important_file.txt", "/path/to/backup_folder")
2. 定时任务:定时发送邮件提醒
场景:每天早上9点自动发送邮件提醒。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import schedule
import time
def send_email():
sender = 'your_email@example.com'
receiver = 'receiver@example.com'
password = 'your_password'
subject = 'Daily Reminder'
body = 'This is your daily reminder.'
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = Header("Reminder", 'utf-8')
msg['To'] = Header("Receiver", 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
try:
server = smtplib.SMTP_SSL('smtp.example.com', 465)
server.login(sender, password)
server.sendmail(sender, [receiver], msg.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
finally:
server.quit()
schedule.every().day.at("09:00").do(send_email)
while True:
schedule.run_pending()
time.sleep(1)
3. 数据抓取:网页内容爬虫
场景:抓取网站新闻标题。
import requests
from bs4 import BeautifulSoup
def scrape_news_titles(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
titles = soup.find_all('h2') # 假设新闻标题在标签中
for title in titles:
print(title.text.strip())# 示例用法
scrape_news_titles('https://news.example.com/latest-news')
现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:691998057【暗号:csdn999】
4. 图片批量重命名
场景:整理图片库,按日期重命名图片。
import os
from datetime import datetime
def rename_files(dir_path):
for i, filename in enumerate(os.listdir(dir_path)):
if filename.endswith('.jpg') or filename.endswith('.png'):
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
new_filename = f"img_{timestamp}_{i}.{filename.split('.')[-1]}"
os.rename(os.path.join(dir_path, filename), os.path.join(dir_path, new_filename))
# 示例用法
rename_files('/path/to/images/folder')
5. 日志文件分析
场景:统计错误日志中错误出现次数。
def analyze_logs(log_path, error_keyword):
error_count = 0
with open(log_path, 'r') as file:
for line in file:
if error_keyword in line:
error_count += 1
print(f"Error '{error_keyword}' occurred {error_count} times.")
# 示例用法
analyze_logs('/var/log/application.log', 'Error 500')
6. 文件夹同步
场景:将本地目录与远程服务器的目录同步。
示例代码(使用rsync命令,通过ssh同步):
import subprocess
def sync_folders(local_dir, remote_host, remote_dir, username):
# 构建rsync命令
cmd = f"rsync -avz --progress -e 'ssh' {local_dir}/' {username}@{remote_host}:{remote_dir}"
try:
subprocess.run(cmd, shell=True, check=True)
print("Sync completed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error during sync: {e}")
# 示例用法
sync_folders('/local/path', 'remote.host.com:/remote/path', 'user')
7. 数据库备份
场景:定期将数据库备份到本地或云存储。
示例代码(MySQL数据库备份到本地文件):
import os
import subprocess
def mysql_backup(database, user, password, backup_path):
backup_file = f"{backup_path}/{database}_backup_{datetime.now().strftime('%Y%m%d%H%M%S')}.sql"
cmd = f'mysqldump -u{user} -p{password} {database} > {backup_file}'
subprocess.run(cmd, shell=True)
print(f"Backup saved to {backup_file}")
# 示例用法
mysql_backup('mydb', 'dbuser', 'dbpassword', '/path/to/backups')
8. API监控
场景:定时检测API响应状态并通知异常。
示例代码(使用requests和SMTP发送邮件通知):
import requests
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
def monitor_api(url, expected_status, email_sender, email_receiver, email_password):
response = requests.get(url)
if response.status_code != expected_status:
message = f"API [{url}] returned {response.status_code} at {datetime.now()}"
msg = MIMEText(message)
msg['Subject'] = "API Monitor Alert"
msg['From'] = email_sender
msg['To'] = email_receiver
with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
server.login(email_sender, email_password)
server.sendmail(email_sender, email_receiver, msg.as_string())
print("Alert email sent.")
else:
print("API check passed.")
# 示例用法
monitor_api('https://api.example.com/health', 200, 'sender@example.com', 'receiver@example.com', 'password')
9. 性能测试
场景:模拟高并发请求进行压力测试。
示例代码(使用locust库):
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(5, 15)
@task
def load_test(self):
self.client.get("/")
# 通过命令行执行Locust
# locust -f performance_test.py --host=https://targetsite.com --users=1000 --spawn-rate=100
10. CI/CD流水线脚本
场景:自动部署代码到生产环境。
示例代码(使用fabric库进行SSH操作):
from fabric import Connection
from invoke import run
def deploy_production(host, username, local_archive):
c = Connection(host, user=username)
remote_path = '/var/www/releases/'
with c.cd(remote_path):
c.put(local_archive)
run(f"tar -xzf {os.path.basename(local_archive)}")
run("rm -f {local_archive}")
run("ln -nfs $(ls -t -1 {remote_path} | head -n1) current")
# 示例用法
deploy_production('production.server.com', 'deployuser', '/path/to/app.tar.gz')
最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走!
软件测试面试文档
我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。