python 10个高频率的自动化脚本(干货,速度收藏)

1. 文件操作:自动备份文件

场景:每日自动备份重要文件到指定目录。

import shutilimport datetimedef 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 smtplibfrom email.mime.text import MIMETextfrom email.header import Headerimport scheduleimport timedef 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 requestsfrom bs4 import BeautifulSoupdef 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')

图片

4. 图片批量重命名

场景:整理图片库,按日期重命名图片。

import osfrom datetime import datetimedef 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 subprocessdef 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 osimport subprocessdef 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 requestsimport smtplibfrom email.mime.text import MIMETextfrom datetime import datetimedef 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, betweenclass 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 Connectionfrom invoke import rundef 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')

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值