python自动化脚本|文件|邮件|系统|办公
作者:YXN-python 阅读量:217 发布日期:2023-04-24
文件类
文件备份
import shutil, os
source_folder = r'C:\Users\example\folder'
target_folder = r'D:\backup\folder'
if not os.path.exists(target_folder):
os.makedirs(target_folder)
for foldername, subfolders, filenames in os.walk(source_folder):
for filename in filenames:
source_file = os.path.join(foldername, filename)
target_file = os.path.join(target_folder, filename)
shutil.copy(source_file, target_file)
按文件扩展名排序
# Python脚本用于按文件扩展名对目录中的文件进行排序
import os
from shutil import move
def sort_files(directory_path):
for filename in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, filename)):
file_extension = filename.split('.')[-1]
destination_directory = os.path.join(directory_path, file_extension)
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
move(os.path.join(directory_path, filename),
os.path.join(destination_directory, filename)
删除空文件夹
# 用Python脚本删除目录中的空文件夹
import os
def remove_empty_folders(directory_path):
for root, dirs, files in os.walk(directory_path, topdown=False):
for folder in dirs:
folder_path = os.path.join(root, folder)
if not os.listdir(folder_path):
os.rmdir(folder_path)
邮件类
发送个性化电子邮件
# 用Python脚本向收件人列表发送个性化电子邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_personalized_email(sender_email, sender_password, recipients, subject, body):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
for recipient_email in recipients:
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
此Python脚本使您能够向一组收件人发送个性化的电子邮件。您可以自定义发件人的电子邮件、密码、主题、正文以及收件人电子邮件列表。
请注意,出于安全原因,在使用Gmail时应使用特定于应用程序的密码。
发送电子邮件附件
# 使用Python脚本发送带有文件附件的电子邮件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_email_with_attachment(sender_email, sender_password, recipient_email, subject, body, file_path):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
message.attach(MIMEText(body, 'plain'))
with open(file_path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {file_path}")
message.attach(part)
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
这个Python脚本允许您发送带有文件附件的电子邮件。只需提供发件人的电子邮件、密码、收件人的电子邮件、主题、正文以及要附加的文件路径即可。
自动电子邮件提醒
# Python脚本发送自动电子邮件提醒
import smtplib
from email.mime.text import MIMEText
from datetime import datetime, timedelta
def send_reminder_email(sender_email, sender_password, recipient_email, subject, body, reminder_date):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, sender_password)
now = datetime.now()
reminder_date = datetime.strptime(reminder_date, '%Y-%m-%d')
if now.date() == reminder_date.date():
message = MIMEText(body, 'plain')
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = subject
server.sendmail(sender_email, recipient_email, message.as_string())
server.quit()
此Python脚本根据指定日期发送自动电子邮件提醒。它对于设置重要任务或事件的提醒非常有用,确保您永远不会错过截止日期。
视频图文类
将图像转换为素描图
# 图像转换
import cv2
# 读取图片
img = cv2.imread("img.jpg")
# 灰度
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
invert = cv2.bitwise_not(grey)
# 高斯滤波
blur_img = cv2.GaussianBlur(invert, (7, 7), 0)
inverse_blur = cv2.bitwise_not(blur_img)
sketch_img = cv2.divide(grey, inverse_blur, scale=256.0)
# 保存
cv2.imwrite('sketch.jpg', sketch_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
视频水印
使用此自动化脚本为你的视频添加水印
# 使用 Python 制作视频水印
# pip install moviepy
从moviepy.editor导入*
clip = VideoFileClip("myvideo.mp4", audio=True)
width,height = clip.size
text = TextClip("WaterMark", font='Arial', color='white', fontsize=28)
set_color = text.on_color(size=(clip.w + text.w, text.h-10), color=(0,0,0), pos=(6,'center'), col_opacity=0.6)
set_textPos = set_color.set_pos( lambda pos: (max(width/30,int(width-0.5* width* pos)),max(5*height/6,int(100* pos))) )
Output = CompositeVideoClip([clip, set_textPos])
Output.duration = clip.duration
Output.write_videofile("output.mp4", fps=30, codec='libx264')
系统类
截图
使用此脚本,你可以直接截屏或截取特定区域的屏幕截图。
# 抓取屏幕截图
# pip install pyautogui
# pip install Pillow
from pyautogui import screenshot
import time
from PIL import ImageGrab
# 抓取屏幕截图
def grab_screenshot():
shot = screenshot()
shot.save('my_screenshot.png')
# 抓取特定区域的截图
def grab_screenshot_area():
area = (0, 0, 500, 500)
shot = ImageGrab.grab(area)
shot.save('my_screenshot_area.png')
# 延迟截屏
def grab_screenshot_delay(): time.sleep
(5)
shot = screenshot()
shot.save('my_screenshot_delay.png')
监控 CPU/GPU 温度
# 获取 CPU/GPU 温度
# pip install pythonnet
从 OpenHardwareMonitorLib导入 clr
clr.AddReference("OpenHardwareMonitorLib")
spec = Computer()
spec.GPUEnabled = True
spec.CPUEnabled = True
spec.Open()
# Get CPU Temp
def Cpu_Temp():
while True:
for cpu in range(0, len(spec.Hardware[0].Sensors)):
if "/temperature" in str(spec.Hardware[0].Sensors[cpu ].Identifier):
print(str(spec.Hardware[0].Sensors[cpu].Value))
# Get GPU Temp
def Gpu_Temp()
while True:
for gpu in range(0, len(spec.Hardware[0].Sensors)):
if "/temperature" in str(spec.Hardware[0].Sensors[gpu] .Identifier):
print(str(spec.Hardware[0].Sensors[gpu].Value))
获取电脑的配置信息
# 获取计算机信息
import wmi
def System_spec():
Pc = wmi.WMI()
os_info = Pc.Win32_OperatingSystem()[0]
processor = Pc.Win32_Processor()[0]
Gpu = Pc.Win32_VideoController()[0]
os_name = os_info.Name.encode('utf-8').split(b'|')[0]
ram = float(os_info.TotalVisibleMemorySize) / 1048576
print(f'操作系统: {os_name}')
print(f'CPU: {processor.Name}')
print(f'内存: {ram} GB')
print(f'显卡: {Gpu.Name}')
print("\n计算机信息如上 ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑")
System_spec()
办公类
时间格式转换
########## 将字符串转换为时间对象 from datetime import datetime # 时间字符串 string_time = '2022-04-21 13:30:00' # 将字符串转换为时间对象 time_obj = datetime.strptime(string_time, '%Y-%m-%d %H:%M:%S') # 将时间对象转换为字符串 string_time = time_obj.strftime('%Y-%m-%d %H:%M:%S') # 时间戳 timestamp = 1650649800 # 将时间戳转换为时间对象 time_obj = datetime.fromtimestamp(timestamp) # 将时间对象转换为时间戳 timestamp = int(time_obj.timestamp())
自动化手机
# 自动化手机
# pip install opencv-python
import subprocess
def main_adb(cm):
p = subprocess.Popen(cm.split(''), stdout=subprocess.PIPE, shell=True)
(output, _) = p.communicate()
return output.decode('utf-8 ')
# Swipe
def swipe(x1, y1, x2, y2, duration):
cmd = 'adb shell input swipe {} {} {} {} {}'.format(x1, y1, x2, y2, duration)
return main_adb(命令)
# 点击或点击
def tap(x, y):
cmd = 'adb shell input tap {} {}'.format(x, y)
return main_adb(cmd)
# 拨打电话
def make_call(number):
cmd = f"adb shell am start -a android.intent.action.CALL -d tel:{number}"
return main_adb(cmd)
# 发送短信
def send_sms(number, message):
cmd = 'adb shell am start -a android.intent.action.SENDTO -d sms:{} --es sms_body "{}"'.format(number, message)
return main_adb(cmd)
# 从手机下载文件到电脑
def download_file(file_name):
cmd = 'adb pull /sdcard/{}'.format(file_name)
return main_adb(cmd)
# 截图
def screenshot():
cmd = 'adb shell screencap -p'
return main_adb(cmd)
# 开机关机
def power_off():
cmd = '"adb shell input keyevent 26"'
return main_adb(cmd)
其他类
检查网站状态
# Python脚本,用于检查网站状态
import requests
def check_website_status(url):
response = requests.get(url)
if response.status_code == 200:
# 在此处编写代码以处理成功的响应
else:
# 在此处编写代码以处理不成功的响应
这个Python脚本通过向提供的URL发送HTTP GET请求来检查网站的状态。它有助于监控网站的可用性及其响应代码。
批量获取类方法
在Python中,可以使用反射机制来获取一个类中的所有方法,包括实例方法和类方法。以下是一个示例代码:
class MyClass:
def __init__(self, name):
self.name = name
def my_method1(self):
pass
def my_method2(self):
pass
@classmethod
def my_classmethod(cls):
pass
@staticmethod
def my_staticmethod():
pass
# 获取类的所有方法,包括实例方法和类方法
methods = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# 打印方法名
for method in methods:
print(method)
需要注意的是,这种方法仅仅只能获取到可调用的方法名,但是不能获取到方法的参数信息和返回值信息。如果需要获取到这些信息,可以使用Python内置的`inspect`模块来实现。
YXN-python
2023-04-24