Files
37duAutomation/.codebuddy/skills/37du-Desktop-Auto/references/api-reference.md
T

189 lines
9.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# desktopauto API 速查(按模块)
> 包位置:`libs/desktopauto/desktopauto/`。所有坐标均为**屏幕物理像素**(DPI 已感知)。
> 约定:模板/文字「没找到」返回 `None`/`False`;配置错误(模板不存在、窗口找不到、依赖缺失)抛 `RuntimeError`。
## 门面:`Screen`
```python
Screen(window=None, region=None, threshold=0.85, scales=(1.0,),
gray=True, debug_dir="", activate_before_click=True)
```
| 分组 | 方法 |
|---|---|
| 截图 | `grab()` → `(img, region)`;`screenshot(path="", region=None, window=None)` → 路径 |
| 窗口 | `activate()`(设了 window 才动作);`clone(**kw)` 派生新配置 |
| 识图 | `find(tpl, **kw)` → `Match|None`;`find_all(tpl, **kw)` → `[Match]`;`exists(tpl)`;`find_any([tpl...])` → `(Match, 模板名)`;`wait(tpl, timeout=10, interval=0.5)` |
| 等待 | `wait_gone(tpl, timeout=10)` → bool;`wait_any(templates=(), texts=(), timeout=10, interval=0.5)` → `{kind,target,match}|None` |
| 点击 | `click(tpl, button="left", clicks=1, offset=(0,0), timeout=0, delay_after=0, anchor="center")` → bool;`click_at(x, y, ...)`;`hover(tpl, offset=(0,0))` → bool;`hover_text(text, offset=(0,0))` → bool |
| 按键串 | `send_keys("^a{ENTER}")`;`move_mouse(x, y, relative_to="screen"|"window", speed=)` |
| 文字 | `read_text(min_score=0.0)` → `[TextItem]`;`find_text(text, **kw)`;`find_all_text(text, **kw)`;`text_exists(text)`;`wait_text(text, timeout=10, interval=1.0)`;`click_text(text, ...)`;`ocr_text(sep="\n")` → str |
| 颜色 | `find_color(color, tolerance=12, min_area=4, max_results=0)` → `[ColorMatch]`;`color_exists(color)`;`diff(baseline, tolerance=10, min_area=30)` → dict |
| 输入 | `paste(text, restore=True)`;`type_text(text, method="auto", interval=0.01)`;`press(key, times=1)`;`hotkey(*keys)` |
| 鼠标 | `scroll(notches=3, at=模板或坐标, horizontal=False)`;`drag(src, dst, duration=0.5)`(src/dst 可传模板或坐标) |
`find/find_all/exists/wait/click/...` 都支持单次覆盖:`threshold`、`scales`、`gray`、`window`、`region`、`max_results`。
## 模块级函数(等价于默认全屏 `Screen()`)
```python
from desktopauto import (find, find_all, find_any, exists, wait, wait_gone, wait_any,
click, click_at, hover, hover_text,
read_text, find_text, find_all_text, text_exists, wait_text,
click_text, ocr_text, ocr_available,
paste, type_text, press, hotkey, scroll, drag,
find_color, color_exists, diff, diff_ratio,
image_exists, wait_image, click_image, hover_image,
ocr_text_with_position, wait_text_exists)
```
RPA 指令别名:`image_exists`=exists、`wait_image`=wait、`click_image`=click、`hover_image`=hover、`ocr_text_with_position`=read_text、`wait_text_exists`=wait_text。
## `matcher`(模板匹配)
```python
Match(left, top, width, height, score) # .center / .region / .to_dict()
load_template(template) # 路径或 ndarray → BGR(透明 PNG 白底合成,兼容中文路径)
match_in(image, template, threshold=0.85, scales=(1.0,), gray=True, max_results=0, origin=(0,0))
match_any_in(image, templates, ...) # → (Match|None, 模板下标)
annotate(image, matches, origin=(0,0), color=(0,200,0)) # 画框(调试)
best(matches) # 相似度最高的一条
```
低纹理模板(灰度标准差 < 6)自动改用平方差匹配,避免纯色块误命中。
## `ocr`(文字识别)
```python
TextItem(text, left, top, width, height, score) # .center / .region / .to_dict()
recognize(image, min_score=0.0, sort=True) # → [TextItem],按阅读顺序
offset(items, origin) # 图内坐标 → 屏幕坐标
match_text(items, query, exact=False, regex=False, case_sensitive=False)
best_text(items) # 置信度最高(同分取面积大)
mark_text(image, items, out_path="", only=None, box_color=..., text_color=...) # 中文标签标注图
summarize(items, limit=0)
available() # rapidocr 是否可用
```
匹配默认:包含 + 忽略大小写 + 忽略空白(OCR 常在字间插空格)。
## `window` / `Window`
```python
get_window(title="", exact=False, pid=0, process="", class_name="", index=0, timeout=0.0) -> Window
foreground_window() -> Window|None
find_windows(title="", exact=False, pid=0, process="", class_name="",
visible_only=True, include_minimized=False) -> [dict]
wait_window(title="", timeout=10, interval=0.3, **kw) -> dict|None
list_windows(keyword="", visible_only=True) -> [(hwnd, title)]
find_window(keyword) -> hwnd
window_info(hwnd) -> dict
child_windows(window) -> [dict]
window_rect(window) -> (left, top, right, bottom) # DWM 扩展边框
activate_window(window|Window) -> hwnd
close_window(window|Window, wait=0.5) # 发 WM_CLOSE
```
`Window`:属性 `hwnd/title/class_name/pid/process/rect/left/top/width/height/center/minimized/visible`;
方法 `info()/exists()/activate()/is_foreground()/minimize()/maximize()/restore()/move(x,y,w,h)/
close(wait)/kill(wait)/wait_closed(timeout)/wait_ready(timeout)/children()/screenshot(path)/
screen(**kw)/to_dict()`。
## `capture`
```python
grab(region=None, window=None) -> (img, region)
save_image(img, path) -> 路径 # 兼容中文路径
screenshot(path="", region=None, window=None) -> 路径
resolve_region(region=None, window=None) -> tuple|None
```
## `colors`(找色 / 差异)
```python
ColorMatch(left, top, width, height, area, color) # .center / .to_dict()
parse_color("#FF3B30" | (255,59,48) | "255,59,48") -> (r, g, b)
find_color(color, tolerance=12, region=None, window=None, min_area=4, max_results=0)
find_colors([c1, c2], ...) -> {颜色: [ColorMatch]} # 一次截图找多色
find_color_in(image, color, tolerance=12, min_area=4, max_results=0, origin=(0,0))
diff(a, b=None, tolerance=10, min_area=30, region=None, window=None)
# → {"changed", "changed_ratio", "boxes", "image"};b=None 时现场截图对比
diff_ratio(a, b=None, tolerance=10, ...) -> float
```
## `keys` / `clipboard`
```python
type_text(text, method="auto", interval=0.01, restore_clipboard=True) # auto:含非 ASCII 走剪贴板
write(text, method="auto") # type_text 别名
press(key, times=1, interval=0.05) # enter/tab/esc/f1-f12/a/1/pageup...
key_down(key) / key_up(key)
hotkey(*keys, interval=0.02) # hotkey("ctrl", "s")
to_vk(key) -> int # 键名 → 虚拟键码(符号键不支持,用 type_text)
send_keys(keys_text, interval=0.02, delay_after=0.0) # 影刀写法:{ENTER} / ^a / %{F4} / abc{ENTER}
parse_send_keys(keys_text) -> [("text","abc"), ("key","ENTER"), ("combo",["ctrl","a"])]
clipboard.set_text(text) / clipboard.get_text() -> str
clipboard.paste(text, restore=True, delay=0.05) -> 被恢复的原文本
```
## `fs`(文件与文件夹)
```python
exists(path) / file_exists(path) / dir_exists(path) -> bool
ensure_dir(path) -> str
make_dir(parent, name="") -> str # 影刀「创建文件夹」
read_text(path, encoding=None) -> str # 编码自动回退 utf-8-sig → gbk
write_text(path, text, encoding="utf-8", append=False) -> str
append_line(path, text) -> str
copy(src, dst, overwrite=True) -> str # dst 是目录时自动拼文件名
move(src, dst, overwrite=True) -> str
delete(path, missing_ok=True) -> bool
list_files(folder, pattern="*", recursive=False, ext=None) -> [str]
newest_file(folder, pattern="*", recursive=False) -> str|None
wait_file(path, timeout=30, interval=0.5, min_size=1) -> bool
wait_file_gone(path, timeout=30, interval=0.5) -> bool
```
## 其他
```python
sleep(seconds=1.0, random_range=None) -> 实际秒数 # 影刀「等待」(可随机)
move_mouse(x, y, relative_to="screen", speed="instant", window=None) # 影刀「移动鼠标」
```
## `process`(运行或打开 / 终止)
```python
run_or_open(target, args=(), wait=0.0) # exe/bat/cmd → Popen;文档/文件夹/网址 → 默认程序打开
launch(target, args=(), cwd=None, wait=0.0) -> Popen
open_path(path) / open_url(url) # 系统默认程序打开
list_processes(name="", with_path=False) -> [{"pid","name","path"}]
is_running(name) -> bool
wait_process(name, timeout=30, interval=0.5, until="start"|"exit") -> bool
kill_process(pid | 进程名 | Window, wait=0.5) -> [pid] # 同名全部终止;找不到抛错
```
## `marking`(离线标记,不动鼠标)
```python
mark(image, templates, out_path="", threshold=0.85, scales=(1.0,), gray=True,
draw_click_point=True) -> {"out","image","size","items","total"}
summarize(result) -> str
```
## CLI
```powershell
python -m desktopauto --mode shot --path shot.png --window "钉钉"
python -m desktopauto --mode exists -t img/btn.png
python -m desktopauto --mode click -t img/btn.png --window "钉钉" --debug-dir debug
python -m desktopauto --mode mark -i shot.png -t "img/a.png,img/b.png" -o marked.png
python -m desktopauto --mode ocr -i shot.png --text "导出,提交" -o hit.png
python -m desktopauto --mode ocr --window "钉钉" --text "工作台" # 实时截屏
```
退出码:0=命中/成功,1=未命中,2=参数或运行错误。输出为 JSON。