-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput_simulator.py
More file actions
70 lines (53 loc) · 1.94 KB
/
Copy pathinput_simulator.py
File metadata and controls
70 lines (53 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
键盘输入模拟模块 - 将文字输入到当前光标位置
使用剪贴板 + Ctrl+V 方案,稳定支持中文等多语言文字输入。
"""
import logging
import time
import pyperclip
import pyautogui
logger = logging.getLogger(__name__)
class InputSimulator:
"""模拟键盘输入,将文字输入到当前焦点窗口的光标位置"""
def __init__(self):
self._original_clipboard = ""
def type_text(self, text: str) -> None:
"""
将文字输入到当前光标位置
原理:将文字写入剪贴板,然后模拟 Ctrl+V 粘贴。
粘贴后自动恢复原始剪贴板内容。
Args:
text: 要输入的文字
"""
if not text:
return
logger.info(f"正在输入文字 ({len(text)} 字符): {text[:50]}{'…' if len(text) > 50 else ''}")
# 保存原始剪贴板内容
self._save_clipboard()
try:
# 写入新文字到剪贴板
pyperclip.copy(text)
time.sleep(0.05) # 等待剪贴板写入完成
# 粘贴到当前光标位置
pyautogui.hotkey('ctrl', 'v')
time.sleep(0.05) # 等待粘贴完成
logger.info("文字输入成功")
except Exception as e:
logger.error(f"键盘输入失败: {e}")
raise
finally:
# 恢复原始剪贴板内容
self._restore_clipboard()
def _save_clipboard(self) -> None:
"""保存当前剪贴板内容"""
try:
self._original_clipboard = pyperclip.paste()
except Exception as e:
logger.warning(f"无法读取剪贴板: {e}")
self._original_clipboard = ""
def _restore_clipboard(self) -> None:
"""恢复剪贴板内容"""
try:
pyperclip.copy(self._original_clipboard)
except Exception as e:
logger.warning(f"无法恢复剪贴板: {e}")