引言:从理论到实践的关键一跃

经过前面六天的理论学习和环境搭建,今天我们将迎来RPA学习旅程中的第一个里程碑——亲手编写并运行一个完整的自动化脚本。如果说之前的理论学习是绘制地图,那么今天的实战就是第一次真正踏上自动化之旅。通过这个看似简单的"自动化打开记事本并保存内容"项目,你将掌握RPA开发中最核心的界面自动化技术,并为后续复杂自动化任务打下坚实基础。

一、为什么选择pyautogui作为RPA入门神器?

1.1 pyautogui在RPA生态中的独特定位

在众多Python自动化库中,pyautogui以其独特的设计哲学脱颖而出:

跨平台一致性:无论是Windows、macOS还是Linux,pyautogui提供完全一致的API接口
零依赖设计:不需要复杂的浏览器驱动或特定应用程序接口
直观的操作模型:模拟真实用户的鼠标键盘操作,学习曲线平缓
强大的屏幕识别:内置图像识别能力,能定位屏幕上特定元素

# pyautogui与其他自动化工具对比
automation_tools_comparison = {
    "pyautogui": {
        "学习难度": "⭐☆☆☆☆ (最简单)",
        "适用场景": "桌面应用、跨平台自动化",
        "侵入性": "非侵入式",
        "依赖程度": "几乎无依赖"
    },
    "selenium": {
        "学习难度": "⭐⭐⭐☆☆ (中等)",
        "适用场景": "Web浏览器自动化",
        "侵入性": "需要浏览器驱动",
        "依赖程度": "中等"
    },
    "pywinauto": {
        "学习难度": "⭐⭐☆☆☆ (较简单)",
        "适用场景": "Windows桌面应用",
        "侵入性": "非侵入式",
        "依赖程度": "Windows专用"
    }
}

1.2 今日项目:自动化记事本操作的全流程解析

我们的目标不仅是完成一个脚本,更是理解自动化背后的完整逻辑链:

项目流程分解:
1. 定位并启动记事本应用程序
2. 等待应用程序完全加载
3. 模拟键盘输入指定文本
4. 触发保存对话框
5. 输入文件名并确认保存
6. 安全关闭应用程序
7. 异常处理和日志记录

这个流程涵盖了RPA开发中最常见的操作模式,是后续所有复杂自动化任务的基础模板。

二、环境深度配置与最佳实践

2.1 创建专业的Python虚拟环境

为什么需要虚拟环境?

# 创建项目专用虚拟环境(Windows)
python -m venv rpa_project_env

# 激活虚拟环境
rpa_project_env\Scripts\activate

# 验证环境
python --version
pip --version

# 创建requirements.txt文件
echo "pyautogui==0.9.53" > requirements.txt
echo "opencv-python==4.8.1.78" >> requirements.txt  # 图像识别依赖
echo "pillow==10.0.0" >> requirements.txt  # 图像处理依赖
echo "pyscreeze==0.1.29" >> requirements.txt  # 屏幕截图功能

虚拟环境管理的最佳实践

  1. 每个项目独立环境,避免包冲突
  2. 使用requirements.txt精确记录依赖版本
  3. 定期更新但保持生产环境稳定
  4. 在团队中使用相同环境配置

2.2 pyautogui的完整安装与验证

# 安装验证脚本 install_verify.py
import sys
import subprocess
import importlib

def check_and_install():
    """检查并安装所需包"""
    required_packages = {
        'pyautogui': '0.9.53',
        'opencv-python': '4.8.1.78',
        'Pillow': '10.0.0',
        'pyscreeze': '0.1.29'
    }
    
    for package, version in required_packages.items():
        try:
            # 尝试导入包
            module = importlib.import_module(package.replace('-', '_'))
            print(f"✓ {package} {getattr(module, '__version__', '未知版本')} 已安装")
        except ImportError:
            print(f"✗ {package} 未安装,正在安装...")
            subprocess.check_call([sys.executable, "-m", "pip", "install", 
                                  f"{package}=={version}"])
            print(f"✓ {package} 安装完成")

if __name__ == "__main__":
    check_and_install()
    print("\n环境验证完成!可以开始编写自动化脚本。")

2.3 开发环境配置技巧

VS Code配置推荐

// .vscode/settings.json
{
    "python.defaultInterpreterPath": "./rpa_project_env/Scripts/python.exe",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.formatting.provider": "black",
    "editor.formatOnSave": true,
    "files.autoSave": "afterDelay",
    "terminal.integrated.shell.windows": "cmd.exe"
}

调试配置

// .vscode/launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: 调试RPA脚本",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": false,
            "env": {
                "PYAUTOGUI_FAST_MODE": "false"
            }
        }
    ]
}

三、pyautogui核心API深度解析

3.1 鼠标控制:从基础到高级

import pyautogui
import time

class MouseController:
    """鼠标控制器深度解析"""
    
    def __init__(self):
        # 获取屏幕尺寸
        self.screen_width, self.screen_height = pyautogui.size()
        print(f"屏幕分辨率: {self.screen_width}x{self.screen_height}")
    
    def basic_mouse_operations(self):
        """基础鼠标操作"""
        # 1. 移动鼠标(绝对位置)
        pyautogui.moveTo(100, 100, duration=1)  # 1秒内移动到(100,100)
        
        # 2. 移动鼠标(相对位置)
        pyautogui.move(50, 50, duration=0.5)  # 向右下移动50像素
        
        # 3. 获取当前鼠标位置
        current_x, current_y = pyautogui.position()
        print(f"当前鼠标位置: ({current_x}, {current_y})")
        
        # 4. 鼠标点击
        pyautogui.click()  # 当前位置点击
        pyautogui.click(x=200, y=200)  # 指定位置点击
        pyautogui.click(button='right')  # 右键点击
        pyautogui.click(clicks=2)  # 双击
        
        # 5. 鼠标拖拽
        pyautogui.dragTo(300, 300, duration=1)  # 拖拽到指定位置
        pyautogui.drag(100, 0, duration=1, button='left')  # 向右拖拽100像素
    
    def advanced_mouse_features(self):
        """高级鼠标功能"""
        # 鼠标滚动
        pyautogui.scroll(10)  # 向上滚动10个单位
        pyautogui.scroll(-10)  # 向下滚动10个单位
        
        # 平滑移动(贝塞尔曲线)
        pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad)
        
        # 鼠标按下和释放(用于复杂交互)
        pyautogui.mouseDown(x=400, y=400, button='left')
        time.sleep(0.5)
        pyautogui.mouseUp(x=600, y=600, button='left')

3.2 键盘控制:精确的输入模拟

class KeyboardController:
    """键盘控制器深度解析"""
    
    def basic_keyboard_operations(self):
        """基础键盘操作"""
        # 1. 输入文本
        pyautogui.write('Hello RPA!', interval=0.1)  # 每个字符间隔0.1秒
        
        # 2. 按键操作
        pyautogui.press('enter')  # 按Enter键
        pyautogui.press(['tab', 'space', 'backspace'])  # 按多个键
        
        # 3. 组合键
        pyautogui.hotkey('ctrl', 's')  # Ctrl+S保存
        pyautogui.hotkey('alt', 'f4')  # Alt+F4关闭窗口
        
        # 4. 按下和释放
        pyautogui.keyDown('shift')  # 按下Shift
        pyautogui.press('a')  # 输入大写A
        pyautogui.keyUp('shift')  # 释放Shift
    
    def special_key_handling(self):
        """特殊按键处理"""
        special_keys = {
            '功能键': ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 
                     'f7', 'f8', 'f9', 'f10', 'f11', 'f12'],
            '导航键': ['home', 'end', 'pageup', 'pagedown', 
                     'up', 'down', 'left', 'right'],
            '控制键': ['ctrl', 'alt', 'shift', 'win', 'cmd'],
            '编辑键': ['insert', 'delete', 'backspace', 'enter', 'tab', 'escape'],
            '多媒体键': ['volumemute', 'volumeup', 'volumedown']
        }
        
        # 使用示例
        pyautogui.press(special_keys['功能键'][5])  # 按F5刷新

3.3 屏幕与图像识别:智能定位元素

class ScreenController:
    """屏幕控制器深度解析"""
    
    def screen_operations(self):
        """屏幕操作"""
        # 1. 截图
        screenshot = pyautogui.screenshot()  # 全屏截图
        screenshot.save('full_screen.png')
        
        # 2. 区域截图
        region_screenshot = pyautogui.screenshot(region=(0, 0, 300, 400))
        region_screenshot.save('region.png')
        
        # 3. 获取像素颜色
        pixel_color = pyautogui.pixel(100, 200)
        print(f"坐标(100,200)的颜色: {pixel_color}")
        
        # 4. 像素颜色匹配
        is_match = pyautogui.pixelMatchesColor(100, 200, (255, 255, 255))
        print(f"颜色匹配: {is_match}")
    
    def image_recognition(self, image_path):
        """图像识别定位"""
        try:
            # 在屏幕上查找图像
            location = pyautogui.locateOnScreen(image_path, confidence=0.9)
            if location:
                center = pyautogui.center(location)
                print(f"找到图像,中心位置: {center}")
                return center
            else:
                print("未找到图像")
                return None
        except pyautogui.ImageNotFoundException:
            print("图像识别失败")
            return None

四、实战项目:自动化记事本完整实现

4.1 项目架构设计

import pyautogui
import time
import sys
import os
from datetime import datetime

class NotepadAutomation:
    """记事本自动化主类"""
    
    def __init__(self, text_to_write="Hello RPA!"):
        # 初始化配置
        self.text = text_to_write
        self.filename = "rpa_demo.txt"
        self.safety_enabled = True
        self.log_file = "automation_log.txt"
        
        # 设置pyautogui参数
        pyautogui.PAUSE = 1.0  # 每个动作后暂停1秒
        pyautogui.FAILSAFE = True  # 启用安全模式
        
        # 日志初始化
        self.setup_logging()
        
    def setup_logging(self):
        """设置日志系统"""
        log_header = f"""
        ========================================
        RPA自动化日志 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        ========================================
        """
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(log_header)
    
    def log_action(self, action, status="SUCCESS", details=""):
        """记录操作日志"""
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
        log_entry = f"[{timestamp}] {action}: {status} {details}\n"
        
        print(log_entry.strip())  # 控制台输出
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(log_entry)

4.2 核心功能实现

    def open_notepad(self):
        """打开记事本应用程序"""
        self.log_action("开始打开记事本")
        
        try:
            # 方法1: 使用Windows运行命令(最可靠)
            pyautogui.hotkey('win', 'r')  # Win+R打开运行对话框
            time.sleep(0.5)
            
            pyautogui.write('notepad')  # 输入notepad
            time.sleep(0.2)
            
            pyautogui.press('enter')  # 按Enter
            time.sleep(2)  # 等待记事本启动
            
            # 验证记事本是否打开
            if self.verify_notepad_open():
                self.log_action("打开记事本", "SUCCESS", "记事本已成功打开")
                return True
            else:
                self.log_action("打开记事本", "FAILED", "无法验证记事本窗口")
                return False
                
        except Exception as e:
            self.log_action("打开记事本", "ERROR", str(e))
            return False
    
    def verify_notepad_open(self):
        """验证记事本是否成功打开"""
        try:
            # 查找记事本窗口的特定特征
            # 检查标题栏或特定菜单项
            
            # 方法1: 检查屏幕特定区域颜色
            # 记事本标题栏通常是特定颜色
            
            # 方法2: 尝试获取焦点
            pyautogui.click(100, 100)  # 点击确保窗口激活
            
            # 等待窗口完全加载
            time.sleep(1)
            
            # 简单验证:检查是否能输入文本
            test_text = "TEST"
            pyautogui.write(test_text)
            time.sleep(0.5)
            pyautogui.hotkey('ctrl', 'a')  # 全选
            pyautogui.press('backspace')  # 删除
            
            return True
            
        except Exception as e:
            self.log_action("验证记事本", "ERROR", str(e))
            return False

4.3 文本输入与保存功能

    def input_text(self):
        """在记事本中输入文本"""
        self.log_action("开始输入文本")
        
        try:
            # 确保记事本窗口激活
            pyautogui.click(100, 100)
            time.sleep(0.5)
            
            # 清空可能存在的文本
            pyautogui.hotkey('ctrl', 'a')
            time.sleep(0.2)
            pyautogui.press('backspace')
            time.sleep(0.2)
            
            # 输入目标文本
            pyautogui.write(self.text, interval=0.1)
            time.sleep(0.5)
            
            # 验证输入
            # 可以通过截图或OCR验证,这里简化处理
            
            self.log_action("输入文本", "SUCCESS", 
                          f"已输入文本: {self.text}")
            return True
            
        except Exception as e:
            self.log_action("输入文本", "ERROR", str(e))
            return False
    
    def save_file(self):
        """保存文件"""
        self.log_action("开始保存文件")
        
        try:
            # 打开保存对话框
            pyautogui.hotkey('ctrl', 's')
            time.sleep(1)  # 等待保存对话框
            
            # 输入文件名
            pyautogui.write(self.filename, interval=0.05)
            time.sleep(0.5)
            
            # 确认保存
            pyautogui.press('enter')
            time.sleep(1)
            
            # 处理覆盖确认(如果文件已存在)
            if self.check_file_exists():
                try:
                    # 尝试点击"是"按钮确认覆盖
                    # 这里可以使用图像识别定位按钮
                    pyautogui.press('left')  # 导航到"是"按钮
                    time.sleep(0.2)
                    pyautogui.press('enter')  # 确认
                except:
                    pass
            
            # 验证文件是否保存成功
            if os.path.exists(self.filename):
                self.log_action("保存文件", "SUCCESS", 
                              f"文件已保存: {self.filename}")
                return True
            else:
                self.log_action("保存文件", "WARNING", 
                              "文件可能未正确保存")
                return False
                
        except Exception as e:
            self.log_action("保存文件", "ERROR", str(e))
            return False
    
    def check_file_exists(self):
        """检查文件是否已存在"""
        return os.path.exists(self.filename)
    
    def close_notepad(self):
        """关闭记事本"""
        self.log_action("开始关闭记事本")
        
        try:
            # 方法1: 使用快捷键关闭
            pyautogui.hotkey('alt', 'f4')
            time.sleep(1)
            
            # 处理未保存提示(如果有)
            # 通常保存后关闭不会出现,但安全起见
            try:
                pyautogui.press('enter')  # 确认关闭
                time.sleep(0.5)
            except:
                pass
            
            self.log_action("关闭记事本", "SUCCESS")
            return True
            
        except Exception as e:
            self.log_action("关闭记事本", "ERROR", str(e))
            return False

4.4 完整工作流集成

    def run_full_workflow(self):
        """执行完整的工作流程"""
        print("=" * 50)
        print("开始执行记事本自动化工作流")
        print("=" * 50)
        
        workflow_steps = [
            ("打开记事本", self.open_notepad),
            ("输入文本", self.input_text),
            ("保存文件", self.save_file),
            ("关闭记事本", self.close_notepad)
        ]
        
        results = []
        for step_name, step_function in workflow_steps:
            print(f"\n正在执行: {step_name}")
            result = step_function()
            results.append((step_name, result))
            
            if not result:
                print(f"步骤失败: {step_name}")
                self.handle_failure(step_name)
                break
            
            # 步骤间暂停
            time.sleep(1)
        
        # 输出执行报告
        self.generate_report(results)
        
        return all(result for _, result in results)
    
    def handle_failure(self, failed_step):
        """处理失败情况"""
        print(f"\n⚠️ 自动化在步骤'{failed_step}'失败")
        print("正在执行清理操作...")
        
        # 尝试恢复操作
        pyautogui.press('esc')  # 按ESC取消可能打开的对话框
        time.sleep(1)
        
        # 尝试关闭所有窗口
        for _ in range(3):
            pyautogui.hotkey('alt', 'f4')
            time.sleep(0.5)
        
        print("清理完成,请检查日志文件获取详细信息")
    
    def generate_report(self, results):
        """生成执行报告"""
        print("\n" + "=" * 50)
        print("自动化执行报告")
        print("=" * 50)
        
        successful_steps = sum(1 for _, result in results if result)
        total_steps = len(results)
        
        print(f"总步骤数: {total_steps}")
        print(f"成功步骤: {successful_steps}")
        print(f"成功率: {(successful_steps/total_steps)*100:.1f}%")
        
        print("\n详细结果:")
        for step_name, result in results:
            status = "✓ 成功" if result else "✗ 失败"
            print(f"  {step_name}: {status}")
        
        print(f"\n日志文件: {self.log_file}")
        print(f"生成的文件: {self.filename}")

五、FAILSAFE安全机制深度解析

5.1 FAILSAFE的工作原理

安全机制的核心思想

启用FAILSAFE后:
1. 持续监控鼠标位置
2. 当鼠标移动到屏幕左上角(0,0)
3. 立即停止所有pyautogui操作
4. 抛出pyautogui.FailSafeException异常
5. 防止自动化脚本失控

5.2 安全机制的最佳实践

class EnhancedSafetyMechanism:
    """增强型安全机制"""
    
    def __init__(self):
        self.safety_zones = {
            'emergency_stop': (0, 0, 50, 50),  # 左上角紧急停止区域
            'pause_zone': (0, 100, 50, 150),   # 暂停区域
            'slow_zone': (0, 200, 50, 250)     # 慢速执行区域
        }
        
    def enable_enhanced_safety(self):
        """启用增强安全模式"""
        # 基础FAILSAFE
        pyautogui.FAILSAFE = True
        
        # 自定义安全监控线程
        import threading
        safety_thread = threading.Thread(target=self.safety_monitor)
        safety_thread.daemon = True
        safety_thread.start()
        
        print("增强安全模式已启用")
    
    def safety_monitor(self):
        """安全监控线程"""
        while True:
            x, y = pyautogui.position()
            
            # 检查紧急停止区域
            if self.is_in_zone(x, y, self.safety_zones['emergency_stop']):
                print("⚠️ 检测到紧急停止信号!")
                self.emergency_stop()
                break
            
            # 检查暂停区域
            elif self.is_in_zone(x, y, self.safety_zones['pause_zone']):
                if not hasattr(self, 'paused'):
                    print("⏸️ 检测到暂停信号")
                    self.pause_execution()
            
            # 检查慢速区域
            elif self.is_in_zone(x, y, self.safety_zones['slow_zone']):
                pyautogui.PAUSE = 2.0  # 增加操作间隔
            
            time.sleep(0.1)  # 每100毫秒检查一次
    
    def is_in_zone(self, x, y, zone):
        """检查坐标是否在指定区域内"""
        zone_x, zone_y, width, height = zone
        return (zone_x <= x <= zone_x + width and 
                zone_y <= y <= zone_y + height)
    
    def emergency_stop(self):
        """紧急停止所有自动化操作"""
        # 停止所有pyautogui操作
        pyautogui._pyautogui_x11._display.record_disable_context()
        print("所有自动化操作已停止")
        
        # 记录停止事件
        with open('emergency_stop.log', 'a') as f:
            f.write(f"紧急停止于: {datetime.now()}\n")
    
    def pause_execution(self):
        """暂停执行"""
        self.paused = True
        print("执行已暂停,移动鼠标离开暂停区域以继续...")
        
        while self.paused:
            x, y = pyautogui.position()
            if not self.is_in_zone(x, y, self.safety_zones['pause_zone']):
                self.paused = False
                print("▶️ 继续执行")
            time.sleep(0.5)

5.3 实际应用中的安全策略

def safe_automation_wrapper(func):
    """安全自动化装饰器"""
    def wrapper(*args, **kwargs):
        print("安全检查启动...")
        
        # 检查FAILSAFE是否启用
        if not pyautogui.FAILSAFE:
            print("警告: FAILSAFE未启用!")
            response = input("是否继续? (y/n): ")
            if response.lower() != 'y':
                return None
        
        # 检查屏幕锁定状态
        if is_screen_locked():
            print("屏幕已锁定,无法执行自动化")
            return None
        
        # 检查用户活动
        if has_recent_user_activity():
            print("检测到用户活动,等待5秒...")
            time.sleep(5)
        
        try:
            # 执行自动化函数
            result = func(*args, **kwargs)
            print("自动化执行完成")
            return result
            
        except pyautogui.FailSafeException:
            print("安全机制触发:用户请求停止")
            return None
            
        except Exception as e:
            print(f"自动化执行出错: {e}")
            return None
    
    return wrapper

@safe_automation_wrapper
def safe_notepad_automation():
    """安全的记事本自动化"""
    automator = NotepadAutomation("安全的RPA演示")
    return automator.run_full_workflow()

六、调试技巧与常见问题解决方案

6.1 实用的调试工具

class RPADebugger:
    """RPA调试工具类"""
    
    @staticmethod
    def visualize_mouse_movement():
        """可视化鼠标移动路径"""
        import matplotlib.pyplot as plt
        
        positions = []
        print("开始记录鼠标移动,移动鼠标到结束位置...")
        
        start_time = time.time()
        while time.time() - start_time < 10:  # 记录10秒
            positions.append(pyautogui.position())
            time.sleep(0.1)
        
        # 绘制路径
        x_coords = [p[0] for p in positions]
        y_coords = [p[1] for p in positions]
        
        plt.figure(figsize=(10, 6))
        plt.plot(x_coords, y_coords, 'b-', alpha=0.5)
        plt.scatter(x_coords, y_coords, c=range(len(positions)), 
                   cmap='viridis', s=50)
        plt.colorbar(label='时间顺序')
        plt.title('鼠标移动路径可视化')
        plt.xlabel('X坐标')
        plt.ylabel('Y坐标')
        plt.show()
    
    @staticmethod
    def record_automation_session():
        """录制自动化会话"""
        from PIL import ImageGrab
        import cv2
        import numpy as np
        
        print("开始录制自动化会话(10秒)...")
        frames = []
        
        for i in range(100):  # 录制10秒(每秒10帧)
            screenshot = ImageGrab.grab()
            frame = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
            frames.append(frame)
            time.sleep(0.1)
        
        # 保存为视频
        height, width = frames[0].shape[:2]
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        out = cv2.VideoWriter('automation_session.avi', 
                             fourcc, 10.0, (width, height))
        
        for frame in frames:
            out.write(frame)
        out.release()
        
        print("录制已保存为 automation_session.avi")

6.2 常见问题及解决方案

问题1:脚本在不同分辨率屏幕上运行不一致

def resolution_independent_click(element_image, confidence=0.9):
    """分辨率无关的点击"""
    # 使用图像识别而不是绝对坐标
    location = pyautogui.locateOnScreen(element_image, confidence=confidence)
    if location:
        center = pyautogui.center(location)
        pyautogui.click(center)
        return True
    return False

问题2:应用程序响应慢导致操作失败

def wait_for_element(image_path, timeout=30, interval=0.5):
    """等待元素出现"""
    start_time = time.time()
    while time.time() - start_time < timeout:
        try:
            location = pyautogui.locateOnScreen(image_path, confidence=0.9)
            if location:
                return location
        except:
            pass
        time.sleep(interval)
    raise TimeoutError(f"未找到元素: {image_path}")

问题3:多语言系统兼容性问题

def multi_language_save():
    """多语言保存支持"""
    save_hotkeys = [
        ['ctrl', 's'],  # 大多数语言
        ['command', 's'],  # Mac系统
        ['ctrl', 'g'],  # 某些德语系统
    ]
    
    for hotkey in save_hotkeys:
        try:
            pyautogui.hotkey(*hotkey)
            time.sleep(1)
            # 检查保存对话框是否出现
            if check_save_dialog():
                return True
        except:
            continue
    
    return False

七、项目扩展与进阶学习路径

7.1 项目扩展建议

  1. 添加GUI界面:使用tkinter或PyQt创建控制面板
  2. 支持批量处理:从文件读取多个文本内容并分别保存
  3. 添加定时功能:在指定时间自动执行
  4. 集成OCR验证:验证输入的文本是否正确显示
  5. 添加邮件通知:执行完成后发送邮件报告

7.2 完整项目代码

"""
notepad_automator.py
完整的记事本自动化脚本
"""

import pyautogui
import time
import sys
import os
from datetime import datetime

def main():
    """主函数"""
    print("记事本自动化脚本 v1.0")
    print("=" * 40)
    
    # 启用安全模式
    pyautogui.FAILSAFE = True
    pyautogui.PAUSE = 1.0
    
    try:
        automator = NotepadAutomation("Hello RPA from Python!")
        success = automator.run_full_workflow()
        
        if success:
            print("\n🎉 自动化执行成功完成!")
            print("恭喜你完成了第一个RPA项目!")
        else:
            print("\n⚠️ 自动化执行遇到问题")
            print("请检查日志文件查看详情")
    
    except KeyboardInterrupt:
        print("\n用户中断执行")
    except pyautogui.FailSafeException:
        print("\n安全机制触发:脚本已停止")
    except Exception as e:
        print(f"\n发生错误: {e}")

if __name__ == "__main__":
    main()

结语:从第一个脚本到自动化专家

通过今天的学习,你已经完成了从RPA理论到实践的关键跨越。这个简单的记事本自动化项目虽然基础,但包含了RPA开发的所有核心要素:界面控制、流程编排、异常处理和安全性设计

记住这个项目中学习到的关键点:

  1. 安全第一:始终启用FAILSAFE机制
  2. 稳健设计:添加适当的等待和验证
  3. 日志记录:保留完整的操作记录
  4. 错误处理:优雅地处理各种异常情况

这个项目是你RPA旅程的起点,而不是终点。接下来,你可以尝试:

  1. 自动化更复杂的应用程序(如Excel、浏览器)
  2. 添加图像识别和OCR功能
  3. 创建可配置的工作流系统
  4. 学习RPA调度和监控
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐