Files
37duAutomation/libs/desktopauto/desktopauto/process.py
T

193 lines
7.6 KiB
Python
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.
# -*- coding: utf-8 -*-
"""进程:运行或打开程序/文件/网址、查询是否在运行、终止程序。
对应 RPA 的「运行或打开」「终止程序」:
- run_or_open:.exe/.bat → 启动;文档/文件夹/网址 → 默认程序打开
- list_processes / is_running / wait_process:查进程
- kill_process:按 pid / 进程名 / Window 对象终止(等价于任务管理器结束进程)
"""
from __future__ import annotations
import ctypes
import os
import subprocess
import time
from ctypes import wintypes
from typing import List, Optional, Sequence, Union
from ._win32 import _process_name, require_windows, terminate_process
TH32CS_SNAPPROCESS = 0x00000002
_INVALID_HANDLE = -1
# 走 subprocess 启动的扩展名(其余交给系统默认程序)
_EXEC_EXTS = (".exe", ".bat", ".cmd", ".com")
class PROCESSENTRY32W(ctypes.Structure):
_fields_ = [
("dwSize", wintypes.DWORD),
("cntUsage", wintypes.DWORD),
("th32ProcessID", wintypes.DWORD),
("th32DefaultHeapID", ctypes.c_void_p),
("th32ModuleID", wintypes.DWORD),
("cntThreads", wintypes.DWORD),
("th32ParentProcessID", wintypes.DWORD),
("pcPriClassBase", ctypes.c_long),
("dwFlags", wintypes.DWORD),
("szExeFile", wintypes.WCHAR * 260),
]
# ==================== 查询 ====================
def list_processes(name: str = "", with_path: bool = False) -> List[dict]:
"""枚举进程,返回 [{"pid", "name", "path"}]。
Args:
name: 可执行名过滤(包含匹配、不区分大小写,如 "DingTalk"、"notepad");空=全部。
with_path: 是否补全完整路径(每个进程多一次 OpenProcess,数量大时慢)。
"""
require_windows("进程枚举")
kernel32 = ctypes.windll.kernel32
kernel32.CreateToolhelp32Snapshot.restype = ctypes.c_void_p
kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
kernel32.Process32FirstW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]
kernel32.Process32NextW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]
snap = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
if not snap or snap == _INVALID_HANDLE:
raise RuntimeError("创建进程快照失败")
key = (name or "").strip().lower()
out: List[dict] = []
try:
entry = PROCESSENTRY32W()
entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)
ok = kernel32.Process32FirstW(snap, ctypes.byref(entry))
while ok:
exe = entry.szExeFile or ""
pid = int(entry.th32ProcessID)
if not key or key in exe.lower():
item = {"pid": pid, "name": exe, "path": ""}
if with_path:
item["path"] = _process_name(pid)
out.append(item)
ok = kernel32.Process32NextW(snap, ctypes.byref(entry))
finally:
kernel32.CloseHandle(ctypes.c_void_p(snap))
return out
def is_running(name: str) -> bool:
"""进程是否在运行(按可执行名包含匹配)。"""
return bool(list_processes(name))
def wait_process(name: str, timeout: float = 30.0, interval: float = 0.5,
until: str = "start") -> bool:
"""等待进程出现(until="start")或消失(until="exit"),超时返回 False。"""
if until not in ("start", "exit"):
raise ValueError(f"until 只能是 start / exit,收到:{until}")
deadline = time.time() + max(0.0, float(timeout))
while True:
running = is_running(name)
if (until == "start" and running) or (until == "exit" and not running):
return True
if time.time() >= deadline:
return False
time.sleep(max(0.1, float(interval)))
# ==================== 启动 / 打开 ====================
def launch(target: str, args: Sequence[str] = (), cwd: Optional[str] = None,
wait: float = 0.0) -> subprocess.Popen:
"""启动程序(.exe/.bat/.cmd),返回 Popen。
Args:
target: 可执行文件路径,或 PATH 里的命令名(如 "notepad.exe")。
args: 命令行参数。
cwd: 工作目录。
wait: 启动后等待秒数(给程序一点时间出窗口,配合 wait_process/get_window 用)。
"""
require_windows("启动程序")
target = str(target)
if not target:
raise ValueError("target 不能为空")
cmd: Union[str, List[str]]
if os.path.exists(target):
cmd = [target, *[str(a) for a in args]]
proc = subprocess.Popen(cmd, cwd=cwd,
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0))
else:
# 交给 PATH 解析(命令名);仍找不到时由系统报错
cmd = " ".join([f'"{target}"', *[f'"{a}"' for a in args]])
proc = subprocess.Popen(cmd, cwd=cwd, shell=True,
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0))
if wait and wait > 0:
time.sleep(float(wait))
return proc
def open_path(path: str) -> str:
"""用系统默认程序打开文件 / 文件夹 / 网址,返回原路径。"""
require_windows("打开文件")
p = str(path)
is_url = p.lower().startswith(("http://", "https://", "mailto:", "file://"))
if not (is_url or os.path.exists(p)):
raise RuntimeError(f"路径不存在:{p}")
os.startfile(p) # noqa: S606 等价于双击
return p
def open_url(url: str) -> str:
"""用默认浏览器打开网址。"""
return open_path(url)
def run_or_open(target: str, args: Sequence[str] = (), wait: float = 0.0
) -> Optional[subprocess.Popen]:
"""运行或打开(RPA「运行或打开」):
- `.exe/.bat/.cmd/.com` 或带参数 → 启动进程,返回 Popen;
- 文档 / 文件夹 / 网址 → 用默认程序打开,返回 None。
"""
t = str(target)
ext = os.path.splitext(t)[1].lower()
if ext in _EXEC_EXTS or args:
return launch(t, args=args, wait=wait)
open_path(t)
return None
# ==================== 终止 ====================
def kill_process(target: Union[int, str], wait: float = 0.5) -> List[int]:
"""终止程序:pid / 进程名 / Window 对象(有 .pid 属性)都支持,返回被终止的 pid 列表。
- 传进程名时,同名的**所有**实例都会被终止(如 3 个 notepad 全关);
- 找不到进程直接抛错(不会静默什么都不做)。
"""
require_windows("终止进程")
pids: List[int] = []
if isinstance(target, int):
pids = [int(target)]
elif isinstance(target, str):
hits = list_processes(target)
pids = [h["pid"] for h in hits]
if not pids:
raise RuntimeError(f"未找到进程:{target}(进程名是否写错?)")
elif hasattr(target, "pid"): # Window 对象(鸭子类型,避免循环导入)
pids = [int(getattr(target, "pid"))]
else:
raise ValueError(f"kill_process 不支持的目标类型:{type(target).__name__}")
failed: List[str] = []
for pid in pids:
try:
terminate_process(pid, wait=0)
except Exception as e: # noqa: BLE001 权限不足等
failed.append(f"{pid}({e})")
if wait and wait > 0:
time.sleep(float(wait))
if failed and len(failed) == len(pids):
raise RuntimeError(f"终止进程失败:{', '.join(failed)}")
return pids