You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:如何用Python获取其他程序高亮文本并替换为脚本输出

实现方案

核心思路

通过模拟系统剪贴板操作+键盘快捷键,完成「获取选中文本→处理→替换选中内容」的流程:

  1. 模拟复制快捷键(Ctrl+C/Command+C),将选中文本存入剪贴板
  2. 读取剪贴板内容作为脚本输入,执行自定义处理逻辑
  3. 将处理后的内容写入剪贴板,模拟粘贴快捷键(Ctrl+V/Command+V)替换原选中内容

依赖库安装

需要用到两个Python库实现模拟操作和剪贴板控制,执行以下命令安装:

pip install pyautogui pyperclip platform

完整代码示例

import pyautogui
import pyperclip
import time
import platform

def get_selected_text():
    # 清空剪贴板避免残留内容干扰
    pyperclip.copy("")
    # 根据系统选择复制快捷键
    os_name = platform.system()
    copy_hotkey = ('command', 'c') if os_name == 'Darwin' else ('ctrl', 'c')
    # 模拟复制操作
    pyautogui.hotkey(*copy_hotkey)
    # 等待剪贴板内容更新(部分程序响应较慢,可适当调整时长)
    time.sleep(0.2)
    return pyperclip.paste()

def process_text(input_text):
    # --------------------------
    # 这里替换成你的自定义处理逻辑
    # 示例:将文本转为大写
    return input_text.upper()
    # --------------------------

def replace_selected_text(output_text):
    # 将处理后的内容写入剪贴板
    pyperclip.copy(output_text)
    # 根据系统选择粘贴快捷键
    os_name = platform.system()
    paste_hotkey = ('command', 'v') if os_name == 'Darwin' else ('ctrl', 'v')
    # 模拟粘贴操作替换原内容
    pyautogui.hotkey(*paste_hotkey)

if __name__ == "__main__":
    selected_content = get_selected_text()
    if selected_content.strip():  # 仅当有有效选中内容时执行处理
        processed_content = process_text(selected_content)
        replace_selected_text(processed_content)

注意事项

  • 调整time.sleep()的时长:如果某些程序复制/粘贴响应慢,可适当增加等待时间(比如0.3-0.5秒)
  • 特殊程序兼容问题:少数软件(如部分终端、加密应用)可能不支持标准复制粘贴快捷键,这种情况下需要针对性调整(比如通过系统API直接读取选中内容,但实现复杂度会更高)
  • 权限问题:在Windows/macOS上,可能需要授予脚本访问屏幕控制、剪贴板的权限,否则会报错

内容的提问来源于stack exchange,提问作者Romi123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:40:31