自动化日常任务的 15 大 Python 脚本

B站影视 2025-01-01 08:18 2

摘要:from PIL import Imagedef resize_image(image_path, output_path, size): with Image.open(image_path) as img: img.resize(size).save(ou

from PIL import Imagedef resize_image(image_path, output_path, size): with Image.open(image_path) as img: img.resize(size).save(output_path)import requestsimport timedef monitor_website(url, interval): prev_content = None while True: response = requests.get(url) if response.text != prev_content: print("Website updated!") prev_content = response.text time.sleep(interval)import subprocessdef backup_mysql(user, password, db_name, output): cmd = f"mysqldump -u {user} -p{password} {db_name} > {output}" subprocess.run(cmd, shell=True)from slack_sdk import WebClientdef send_slack_message(token, channel, text): client = WebClient(token=token) client.chat_postMessage(channel=channel, text=text)获取天气数据。库:请求import requestsdef get_weather(api_key, city): url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}" return requests.get(url).json将文本转换为语音。库: pyttsx3import pyttsx3def text_to_speech(text): engine = pyttsx3.init engine.say(text) engine.runAndWait使用 API 转换货币。库: forex-pythonfrom forex_python.converter import CurrencyRatesdef convert_Currency(amount, from_currency, to_currency): c = CurrencyRates return c.convert(from_currency, to_currency, amount)计划 Python 任务。库:scheduleimport scheduleimport timedef task: print("Task running!")schedule.every.day.at("10:00").do(task)while True: schedule.run_pending time.sleep(1)将通知推送到您的手机。库: pushbulletfrom pushbullet import Pushbulletdef send_notification(api_key, title, body): pb = Pushbullet(api_key) pb.push_note(title, body)删除目录中的旧文件。库: os, timeimport osimport timedef cleanup(directory, days): now = time.time for file in os.listdir(directory): filepath = os.path.join(directory, file) if os.stat(filepath).st_mtime 获取股票价格。库: yfinanceimport yfinance as yfdef get_stock_price(ticker): stock = yf.Ticker(ticker) return stock.history(period="1d")["Close"]为文本或 URL 生成 QR 码。库: qrcodeimport qrcodedef generate_qr(data, filename): qr = qrcode.make(data) qr.save(filename)自动按下键盘。库: pyautoguiimport pyautoguidef automate_typing(text): pyautogui.typewrite(text)自动化 git push/pull。库:subprocessimport subprocessdef git_push(message): subprocess.run(["git", "add", "."]) subprocess.run(["git", "commit", "-m", message]) subprocess.run(["git", "push"])import timestart_time = time.time# Do some workprint("Time spent:", time.time - start_time)

这些脚本可以帮助您节省时间并简化重复性任务。将这些与 cron 作业或任务调度程序相结合,以解锁强大的自动化功能!

来源:自由坦荡的湖泊AI一点号

相关推荐