wholocks 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: windows-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ python-version: ["3.9", "3.12", "3.14"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: astral-sh/setup-uv@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - run: uv sync --extra dev
21
+ - run: uv run pytest -q
@@ -0,0 +1,30 @@
1
+ name: publish
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ jobs:
8
+ build:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - uses: astral-sh/setup-uv@v5
13
+ - run: uv build
14
+ - uses: actions/upload-artifact@v4
15
+ with:
16
+ name: dist
17
+ path: dist/
18
+
19
+ publish:
20
+ needs: build
21
+ runs-on: ubuntu-latest
22
+ environment: pypi
23
+ permissions:
24
+ id-token: write
25
+ steps:
26
+ - uses: actions/download-artifact@v4
27
+ with:
28
+ name: dist
29
+ path: dist/
30
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ .uv/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .mypy_cache/
wholocks-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wholocks contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,138 @@
1
+ Metadata-Version: 2.5
2
+ Name: wholocks
3
+ Version: 0.1.0
4
+ Summary: Find out which Windows process is locking a file. No admin rights, no Sysinternals.
5
+ Project-URL: Homepage, https://github.com/Python-and-Cpp/wholocks
6
+ Project-URL: Repository, https://github.com/Python-and-Cpp/wholocks
7
+ Project-URL: Issues, https://github.com/Python-and-Cpp/wholocks/issues
8
+ Author: wholocks contributors
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: file-lock,handle,locked-file,node_modules,restart-manager,windows
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Win32 (MS Windows)
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: System :: Systems Administration
25
+ Classifier: Topic :: Utilities
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.9
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Provides-Extra: docs
31
+ Requires-Dist: pillow>=10; extra == 'docs'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # wholocks
35
+
36
+ **Find out which Windows process is locking a file — no admin rights, no Sysinternals.**
37
+
38
+ ![wholocks demo](https://raw.githubusercontent.com/Python-and-Cpp/wholocks/main/docs/demo.gif)
39
+
40
+ Windows only ever says *"The process cannot access the file because it is being used by another process."*
41
+ `wholocks` tells you **which** process, so you can stop guessing and go close it.
42
+
43
+ Works on files and on whole directories (it walks the tree), and exits with `1` when something
44
+ is locked — so it drops straight into scripts, Makefiles and CI without parsing output.
45
+
46
+ ## Install
47
+
48
+ ```console
49
+ uvx wholocks path\to\file # run once, nothing installed
50
+ uv tool install wholocks # or: pipx install wholocks
51
+ pip install wholocks
52
+ ```
53
+
54
+ Requires Python 3.9+ on Windows. No runtime dependencies.
55
+
56
+ ## Usage
57
+
58
+ ```console
59
+ wholocks build\app.exe # single file
60
+ wholocks .\build # recursive directory scan
61
+ wholocks --no-deep .\build # only files directly inside
62
+ wholocks --json .\build # machine-readable output
63
+ wholocks -q .\build .\dist # quiet: print only locked paths
64
+ ```
65
+
66
+ Example output for a locked file:
67
+
68
+ ```console
69
+ $ wholocks .\dist
70
+ D:\proj\dist
71
+ PID 24916 Code.exe (Visual Studio Code · MainWindow)
72
+ C:\Users\me\AppData\Local\Programs\Microsoft VS Code\Code.exe
73
+ ```
74
+
75
+ `wholocks` reports the PID, the process image, the application name, and whether the holder is
76
+ a window, a console, a service or a critical process — enough to decide whether to close it,
77
+ restart it, or run as administrator.
78
+
79
+ ### Exit codes
80
+
81
+ | Code | Meaning |
82
+ | --- | --- |
83
+ | `0` | nothing is locking the path |
84
+ | `1` | at least one process holds the path |
85
+ | `2` | query failed (path missing, access denied, invalid arguments) |
86
+
87
+ ```powershell
88
+ if (wholocks .\dist) { Write-Host "still locked, aborting build" }
89
+ ```
90
+
91
+ ## Python API
92
+
93
+ ```python
94
+ from wholocks import who_locks
95
+
96
+ for holder in who_locks(r"C:\proj\build"):
97
+ print(holder.pid, holder.image, holder.app_name, holder.kind)
98
+
99
+ # empty list when nothing is holding it
100
+ assert who_locks(r"C:\proj\build") == []
101
+ ```
102
+
103
+ ## How it works
104
+
105
+ It calls the **Restart Manager** API (`rstrtmgr.dll`: `RmStartSession` → `RmRegisterResources`
106
+ → `RmGetList`). This is the exact API Windows installers use to decide whether a file can be
107
+ replaced or a reboot is required, so the results match what Windows itself believes.
108
+
109
+ Compared to the alternatives:
110
+
111
+ - `handle.exe` (Sysinternals) requires downloading a separate tool, usually running elevated,
112
+ and re-resolving PIDs by hand.
113
+ - `psutil` can enumerate modules and open files, but not reliably, and not without elevated
114
+ privileges for other processes.
115
+
116
+ `wholocks` is pure `ctypes`, ships nothing to download, and needs no elevation for your own
117
+ processes.
118
+
119
+ ## Limitations
120
+
121
+ - A directory is expanded into its files. A folder that is only held as some process's *working
122
+ directory* is not reported — that is a Restart Manager characteristic, not a bug.
123
+ - System processes and services may require an elevated shell; in that case `wholocks` exits with
124
+ `2` and tells you so.
125
+ - Network shares and files locked on other machines are out of scope.
126
+ - Large directories are capped by `--max-files` (default 20000) to avoid scanning an entire drive.
127
+
128
+ ## Development
129
+
130
+ ```console
131
+ uv sync --extra dev
132
+ uv run pytest -q
133
+ python scripts/make_demo.py # regenerate docs/demo.gif from a real run
134
+ ```
135
+
136
+ ## License
137
+
138
+ MIT
@@ -0,0 +1,105 @@
1
+ # wholocks
2
+
3
+ **Find out which Windows process is locking a file — no admin rights, no Sysinternals.**
4
+
5
+ ![wholocks demo](https://raw.githubusercontent.com/Python-and-Cpp/wholocks/main/docs/demo.gif)
6
+
7
+ Windows only ever says *"The process cannot access the file because it is being used by another process."*
8
+ `wholocks` tells you **which** process, so you can stop guessing and go close it.
9
+
10
+ Works on files and on whole directories (it walks the tree), and exits with `1` when something
11
+ is locked — so it drops straight into scripts, Makefiles and CI without parsing output.
12
+
13
+ ## Install
14
+
15
+ ```console
16
+ uvx wholocks path\to\file # run once, nothing installed
17
+ uv tool install wholocks # or: pipx install wholocks
18
+ pip install wholocks
19
+ ```
20
+
21
+ Requires Python 3.9+ on Windows. No runtime dependencies.
22
+
23
+ ## Usage
24
+
25
+ ```console
26
+ wholocks build\app.exe # single file
27
+ wholocks .\build # recursive directory scan
28
+ wholocks --no-deep .\build # only files directly inside
29
+ wholocks --json .\build # machine-readable output
30
+ wholocks -q .\build .\dist # quiet: print only locked paths
31
+ ```
32
+
33
+ Example output for a locked file:
34
+
35
+ ```console
36
+ $ wholocks .\dist
37
+ D:\proj\dist
38
+ PID 24916 Code.exe (Visual Studio Code · MainWindow)
39
+ C:\Users\me\AppData\Local\Programs\Microsoft VS Code\Code.exe
40
+ ```
41
+
42
+ `wholocks` reports the PID, the process image, the application name, and whether the holder is
43
+ a window, a console, a service or a critical process — enough to decide whether to close it,
44
+ restart it, or run as administrator.
45
+
46
+ ### Exit codes
47
+
48
+ | Code | Meaning |
49
+ | --- | --- |
50
+ | `0` | nothing is locking the path |
51
+ | `1` | at least one process holds the path |
52
+ | `2` | query failed (path missing, access denied, invalid arguments) |
53
+
54
+ ```powershell
55
+ if (wholocks .\dist) { Write-Host "still locked, aborting build" }
56
+ ```
57
+
58
+ ## Python API
59
+
60
+ ```python
61
+ from wholocks import who_locks
62
+
63
+ for holder in who_locks(r"C:\proj\build"):
64
+ print(holder.pid, holder.image, holder.app_name, holder.kind)
65
+
66
+ # empty list when nothing is holding it
67
+ assert who_locks(r"C:\proj\build") == []
68
+ ```
69
+
70
+ ## How it works
71
+
72
+ It calls the **Restart Manager** API (`rstrtmgr.dll`: `RmStartSession` → `RmRegisterResources`
73
+ → `RmGetList`). This is the exact API Windows installers use to decide whether a file can be
74
+ replaced or a reboot is required, so the results match what Windows itself believes.
75
+
76
+ Compared to the alternatives:
77
+
78
+ - `handle.exe` (Sysinternals) requires downloading a separate tool, usually running elevated,
79
+ and re-resolving PIDs by hand.
80
+ - `psutil` can enumerate modules and open files, but not reliably, and not without elevated
81
+ privileges for other processes.
82
+
83
+ `wholocks` is pure `ctypes`, ships nothing to download, and needs no elevation for your own
84
+ processes.
85
+
86
+ ## Limitations
87
+
88
+ - A directory is expanded into its files. A folder that is only held as some process's *working
89
+ directory* is not reported — that is a Restart Manager characteristic, not a bug.
90
+ - System processes and services may require an elevated shell; in that case `wholocks` exits with
91
+ `2` and tells you so.
92
+ - Network shares and files locked on other machines are out of scope.
93
+ - Large directories are capped by `--max-files` (default 20000) to avoid scanning an entire drive.
94
+
95
+ ## Development
96
+
97
+ ```console
98
+ uv sync --extra dev
99
+ uv run pytest -q
100
+ python scripts/make_demo.py # regenerate docs/demo.gif from a real run
101
+ ```
102
+
103
+ ## License
104
+
105
+ MIT
Binary file
@@ -0,0 +1,59 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "wholocks"
7
+ dynamic = ["version"]
8
+ description = "Find out which Windows process is locking a file. No admin rights, no Sysinternals."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "wholocks contributors" }]
13
+ keywords = [
14
+ "windows",
15
+ "file-lock",
16
+ "locked-file",
17
+ "restart-manager",
18
+ "handle",
19
+ "node_modules",
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 3 - Alpha",
23
+ "Environment :: Win32 (MS Windows)",
24
+ "Intended Audience :: Developers",
25
+ "Intended Audience :: System Administrators",
26
+ "License :: OSI Approved :: MIT License",
27
+ "Operating System :: Microsoft :: Windows",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3.9",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Topic :: System :: Systems Administration",
35
+ "Topic :: Utilities",
36
+ "Typing :: Typed",
37
+ ]
38
+ dependencies = []
39
+
40
+ [project.optional-dependencies]
41
+ dev = ["pytest>=8"]
42
+ docs = ["pillow>=10"]
43
+
44
+ [project.scripts]
45
+ wholocks = "wholocks.cli:main"
46
+
47
+ [project.urls]
48
+ Homepage = "https://github.com/Python-and-Cpp/wholocks"
49
+ Repository = "https://github.com/Python-and-Cpp/wholocks"
50
+ Issues = "https://github.com/Python-and-Cpp/wholocks/issues"
51
+
52
+ [tool.hatch.version]
53
+ path = "src/wholocks/__init__.py"
54
+
55
+ [tool.hatch.build.targets.wheel]
56
+ packages = ["src/wholocks"]
57
+
58
+ [tool.pytest.ini_options]
59
+ testpaths = ["tests"]
@@ -0,0 +1,254 @@
1
+ """生成 README 首屏的演示 GIF。
2
+
3
+ 流程全部基于真实调用:先拉起一个真的占着文件的进程,
4
+ 再真实执行 ``python -m wholocks .\\dist``,把捕获到的输出渲染成终端动画。
5
+
6
+ 用法:
7
+ python scripts/make_demo.py
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ from pathlib import Path
18
+ from typing import List, Optional, Sequence, Tuple
19
+
20
+ from PIL import Image, ImageDraw, ImageFont
21
+
22
+ ROOT = Path(__file__).resolve().parents[1]
23
+ OUTPUT = ROOT / "docs" / "demo.gif"
24
+ DEMO_DIR = ROOT / "dist"
25
+
26
+ WIDTH, HEIGHT = 980, 380
27
+ MARGIN = 16
28
+ TITLE_H = 34
29
+ PAD_X, PAD_Y = 36, 32
30
+ LINE_H = 32
31
+ FONT_SIZE = 19
32
+
33
+ BG = (12, 12, 12)
34
+ OUTER = (23, 23, 23)
35
+ TITLE_BG = (30, 30, 30)
36
+ TEXT = (204, 204, 204)
37
+ PROMPT = (86, 156, 214)
38
+ COMMAND = (255, 255, 255)
39
+ PATH = (78, 193, 255)
40
+ PID_COLOR = (220, 220, 170)
41
+ PROCESS = (137, 209, 133)
42
+ DIM = (128, 128, 128)
43
+ ALERT = (244, 135, 113)
44
+
45
+ Span = Tuple[str, Tuple[int, int, int], bool]
46
+
47
+ FONT = ImageFont.truetype(r"C:\Windows\Fonts\consola.ttf", FONT_SIZE)
48
+ FONT_BOLD = ImageFont.truetype(r"C:\Windows\Fonts\consolab.ttf", FONT_SIZE)
49
+
50
+
51
+ def span_width(spans: Sequence[Span]) -> int:
52
+ total = 0.0
53
+ for text, _color, bold in spans:
54
+ total += FONT_BOLD.getlength(text) if bold else FONT.getlength(text)
55
+ return int(total)
56
+
57
+
58
+ def capture() -> Tuple[str, List[List[Span]], int]:
59
+ """真实跑一次,返回命令、带颜色的输出行和退出码。"""
60
+ DEMO_DIR.mkdir(parents=True, exist_ok=True)
61
+ target = DEMO_DIR / "app.exe"
62
+ target.write_bytes(b"MZ" + b"\x00" * 4096)
63
+
64
+ holder_code = "import sys, time; h = open(sys.argv[1], 'rb'); time.sleep(40)"
65
+ holder = subprocess.Popen(
66
+ [sys.executable, "-c", holder_code, str(target)],
67
+ stdout=subprocess.DEVNULL,
68
+ stderr=subprocess.DEVNULL,
69
+ )
70
+ try:
71
+ time.sleep(1.0)
72
+ env = dict(os.environ, PYTHONPATH=str(ROOT / "src"))
73
+ result = subprocess.run(
74
+ [sys.executable, "-m", "wholocks", ".\\dist"],
75
+ cwd=str(ROOT),
76
+ capture_output=True,
77
+ text=True,
78
+ encoding="utf-8",
79
+ env=env,
80
+ )
81
+ finally:
82
+ holder.terminate()
83
+ try:
84
+ holder.wait(timeout=5)
85
+ except subprocess.TimeoutExpired:
86
+ holder.kill()
87
+ # 只清理自己创建的演示文件,避免误删 dist/ 里已构建的 wheel
88
+ target.unlink(missing_ok=True)
89
+ try:
90
+ DEMO_DIR.rmdir()
91
+ except OSError:
92
+ pass
93
+
94
+ raw_lines = [line.rstrip() for line in result.stdout.splitlines()]
95
+ if not any("PID" in line for line in raw_lines):
96
+ raise SystemExit("没有捕获到占用信息,GIF 未生成:\n" + result.stdout + result.stderr)
97
+ return ".\\dist", [_style(line) for line in raw_lines], result.returncode
98
+
99
+
100
+ def _style(line: str) -> List[Span]:
101
+ if not line:
102
+ return []
103
+ pid_match = re.match(r"^(\s*PID\s+)(\d+)(\s+)(\S+)(\s+)(.*)$", line)
104
+ if pid_match:
105
+ return [
106
+ (pid_match.group(1), DIM, False),
107
+ (pid_match.group(2), PID_COLOR, False),
108
+ (pid_match.group(3), TEXT, False),
109
+ (pid_match.group(4), PROCESS, False),
110
+ (pid_match.group(5), TEXT, False),
111
+ (pid_match.group(6), DIM, False),
112
+ ]
113
+ if line.startswith(" "):
114
+ return [(line, DIM, False)]
115
+ return [(line, PATH, False)]
116
+
117
+
118
+ def draw_window() -> Image.Image:
119
+ image = Image.new("RGB", (WIDTH, HEIGHT), OUTER)
120
+ draw = ImageDraw.Draw(image)
121
+ draw.rounded_rectangle(
122
+ (MARGIN, MARGIN, WIDTH - MARGIN, HEIGHT - MARGIN),
123
+ radius=12,
124
+ fill=BG,
125
+ outline=(45, 45, 45),
126
+ )
127
+ draw.rounded_rectangle(
128
+ (MARGIN, MARGIN, WIDTH - MARGIN, MARGIN + TITLE_H),
129
+ radius=12,
130
+ fill=TITLE_BG,
131
+ )
132
+ draw.rectangle((MARGIN, MARGIN + TITLE_H - 12, WIDTH - MARGIN, MARGIN + TITLE_H), fill=TITLE_BG)
133
+ for index, color in enumerate([(255, 95, 86), (255, 189, 46), (39, 201, 63)]):
134
+ cx = MARGIN + 20 + index * 20
135
+ draw.ellipse((cx - 6, MARGIN + 11, cx + 6, MARGIN + 23), fill=color)
136
+ title = "PowerShell"
137
+ draw.text(
138
+ ((WIDTH - FONT.getlength(title)) / 2, MARGIN + 8),
139
+ title,
140
+ font=FONT,
141
+ fill=(150, 150, 150),
142
+ )
143
+ return image
144
+
145
+
146
+ def draw_frame(
147
+ lines: Sequence[Sequence[Span]],
148
+ shown: int,
149
+ partial_line: Optional[int] = None,
150
+ partial_chars: int = 0,
151
+ ) -> Image.Image:
152
+ image = draw_window()
153
+ draw = ImageDraw.Draw(image)
154
+ y = MARGIN + TITLE_H + 22
155
+ cursor = None
156
+
157
+ for index, spans in enumerate(lines):
158
+ if index >= shown and index != partial_line:
159
+ break
160
+ limit = partial_chars if index == partial_line else None
161
+ x = PAD_X
162
+ drawn_any = False
163
+ for text, color, bold in spans:
164
+ if limit is not None:
165
+ if limit <= 0:
166
+ break
167
+ text = text[:limit]
168
+ limit -= len(text)
169
+ if text:
170
+ draw.text((x, y), text, font=FONT_BOLD if bold else FONT, fill=color)
171
+ x += (FONT_BOLD if bold else FONT).getlength(text)
172
+ drawn_any = True
173
+ if index == partial_line:
174
+ cursor = (x, y + 2)
175
+ y += LINE_H
176
+ if not drawn_any and index == partial_line:
177
+ cursor = (x, y - LINE_H + 2)
178
+
179
+ if cursor:
180
+ draw.rectangle(
181
+ (cursor[0] + 1, cursor[1], cursor[0] + 9, cursor[1] + FONT_SIZE + 3),
182
+ fill=TEXT,
183
+ )
184
+ return image
185
+
186
+
187
+ def build() -> List[Tuple[Image.Image, int]]:
188
+ argument, output_lines, exit_code = capture()
189
+ prompt_spans: List[Span] = [
190
+ ("PS ", PROMPT, False),
191
+ (str(ROOT) + "> ", TEXT, False),
192
+ ]
193
+ command_text = "wholocks " + argument
194
+ command_spans: List[Span] = [(command_text, COMMAND, True)]
195
+ exit_spans: List[Span] = [("$LASTEXITCODE", TEXT, False)]
196
+
197
+ lines: List[List[Span]] = [
198
+ prompt_spans + command_spans,
199
+ *output_lines,
200
+ [],
201
+ prompt_spans + exit_spans,
202
+ [(str(exit_code), ALERT, False)],
203
+ ]
204
+
205
+ prompt_len = len("PS ") + len(str(ROOT)) + 2
206
+ frames: List[Tuple[Image.Image, int]] = []
207
+
208
+ frames.append((draw_frame(lines, 1, partial_line=0, partial_chars=prompt_len), 650))
209
+ for count in range(0, len(command_text) + 1):
210
+ frames.append(
211
+ (draw_frame(lines, 1, partial_line=0, partial_chars=prompt_len + count), 25)
212
+ )
213
+ frames.append((draw_frame(lines, 1), 240))
214
+
215
+ output_start = 1
216
+ for offset in range(len(output_lines) - 1):
217
+ frames.append((draw_frame(lines, output_start + offset + 1), 170))
218
+ frames.append((draw_frame(lines, output_start + len(output_lines)), 850))
219
+
220
+ exit_index = len(lines) - 2
221
+ for count in range(0, len("$LASTEXITCODE") + 1, 2):
222
+ frames.append(
223
+ (draw_frame(lines, exit_index + 1, partial_line=exit_index, partial_chars=prompt_len + count), 28)
224
+ )
225
+ frames.append((draw_frame(lines, len(lines) - 1), 320))
226
+ frames.append((draw_frame(lines, len(lines)), 2600))
227
+ return frames
228
+
229
+
230
+ def main() -> int:
231
+ frames = build()
232
+ OUTPUT.parent.mkdir(parents=True, exist_ok=True)
233
+
234
+ base = frames[-1][0]
235
+ palette = base.quantize(colors=96, method=Image.Quantize.MEDIANCUT)
236
+ prepared = [
237
+ frame.quantize(palette=palette, dither=Image.Dither.NONE) for frame, _ in frames
238
+ ]
239
+ durations = [duration for _, duration in frames]
240
+ prepared[0].save(
241
+ OUTPUT,
242
+ save_all=True,
243
+ append_images=prepared[1:],
244
+ duration=durations,
245
+ loop=0,
246
+ optimize=True,
247
+ disposal=2,
248
+ )
249
+ print("%s %d frames %.0f KB" % (OUTPUT, len(frames), OUTPUT.stat().st_size / 1024))
250
+ return 0
251
+
252
+
253
+ if __name__ == "__main__":
254
+ sys.exit(main())
@@ -0,0 +1,7 @@
1
+ """wholocks —— 查询 Windows 上哪个进程正占用着文件。"""
2
+
3
+ from .core import LockHolder, LockQueryError, who_locks
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ __all__ = ["LockHolder", "LockQueryError", "who_locks", "__version__"]
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
@@ -0,0 +1,97 @@
1
+ """wholocks 命令行入口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from typing import Dict, List, Optional, Sequence
9
+
10
+ from . import __version__
11
+ from .core import LockQueryError, who_locks
12
+
13
+ EXIT_OK = 0
14
+ EXIT_LOCKED = 1
15
+ EXIT_ERROR = 2
16
+
17
+
18
+ def _build_parser() -> argparse.ArgumentParser:
19
+ parser = argparse.ArgumentParser(
20
+ prog="wholocks",
21
+ description="Find out which Windows process is locking a file or directory.",
22
+ epilog="Exit codes: 0 = not locked, 1 = locked, 2 = query failed.",
23
+ )
24
+ parser.add_argument("paths", nargs="+", metavar="PATH", help="file or directory to inspect")
25
+ parser.add_argument("--json", action="store_true", help="machine-readable JSON output")
26
+ parser.add_argument("-q", "--quiet", action="store_true", help="only print locked paths")
27
+ parser.add_argument(
28
+ "--no-deep",
29
+ action="store_true",
30
+ help="for directories, only inspect files directly inside",
31
+ )
32
+ parser.add_argument(
33
+ "--max-files",
34
+ type=int,
35
+ default=20000,
36
+ metavar="N",
37
+ help="max files to scan per directory (default: 20000)",
38
+ )
39
+ parser.add_argument("-V", "--version", action="version", version="%(prog)s " + __version__)
40
+ return parser
41
+
42
+
43
+ def _print_human(results: List[Dict], quiet: bool) -> None:
44
+ for item in results:
45
+ if "error" in item:
46
+ print("%s\n error: %s" % (item["path"], item["error"]), file=sys.stderr)
47
+ continue
48
+
49
+ holders = item["holders"]
50
+ if not holders:
51
+ if not quiet:
52
+ print("%s\n not locked" % item["path"])
53
+ continue
54
+
55
+ print(item["path"])
56
+ for holder in holders:
57
+ label = holder["image"] or "PID %d" % holder["pid"]
58
+ details = []
59
+ if holder["app_name"]:
60
+ details.append(holder["app_name"])
61
+ if holder["service"]:
62
+ details.append("服务 %s" % holder["service"])
63
+ details.append(holder["type"])
64
+ print(" PID %-7d %s (%s)" % (holder["pid"], label, " · ".join(details)))
65
+ if holder["image_path"]:
66
+ print(" %14s %s" % ("", holder["image_path"]))
67
+
68
+
69
+ def main(argv: Optional[Sequence[str]] = None) -> int:
70
+ args = _build_parser().parse_args(argv)
71
+
72
+ results: List[Dict] = []
73
+ failed = False
74
+ for path in args.paths:
75
+ try:
76
+ holders = who_locks(path, deep=not args.no_deep, max_files=args.max_files)
77
+ except (FileNotFoundError, LockQueryError, OSError) as exc:
78
+ failed = True
79
+ results.append({"path": path, "error": str(exc), "holders": []})
80
+ continue
81
+ results.append({"path": path, "holders": [holder.to_dict() for holder in holders]})
82
+
83
+ locked = any(item["holders"] for item in results)
84
+ if args.json:
85
+ json.dump(
86
+ {"locked": locked, "results": results},
87
+ sys.stdout,
88
+ ensure_ascii=False,
89
+ indent=2,
90
+ )
91
+ sys.stdout.write("\n")
92
+ else:
93
+ _print_human(results, quiet=args.quiet)
94
+
95
+ if failed:
96
+ return EXIT_ERROR
97
+ return EXIT_LOCKED if locked else EXIT_OK
@@ -0,0 +1,304 @@
1
+ """基于 Windows Restart Manager 的文件占用查询。
2
+
3
+ rstrtmgr.dll 提供的 RmStartSession / RmRegisterResources / RmGetList 三件套,
4
+ 正是 Windows 安装程序判断「谁占着文件、要不要重启」时用的同一套接口:
5
+ 不需要管理员权限,也不需要 Sysinternals。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ctypes
11
+ import os
12
+ import sys
13
+ from ctypes import wintypes
14
+ from dataclasses import dataclass
15
+ from typing import Dict, List, Optional, Sequence, Tuple
16
+
17
+ CCH_RM_SESSION_KEY = 32
18
+ CCH_RM_MAX_APP_NAME = 255
19
+ CCH_RM_MAX_SVC_NAME = 63
20
+
21
+ ERROR_SUCCESS = 0
22
+ ERROR_ACCESS_DENIED = 5
23
+ ERROR_BAD_ARGUMENTS = 160
24
+ ERROR_MORE_DATA = 234
25
+
26
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
27
+
28
+ # RM_APP_TYPE 枚举
29
+ APP_TYPES = {
30
+ 0: "Unknown",
31
+ 1: "MainWindow",
32
+ 2: "OtherWindow",
33
+ 3: "Service",
34
+ 4: "Explorer",
35
+ 5: "Console",
36
+ 1000: "Critical",
37
+ }
38
+
39
+ _DEFAULT_MAX_FILES = 20_000
40
+ _REGISTER_BATCH = 1_000
41
+ _ERROR_MESSAGES = {
42
+ ERROR_ACCESS_DENIED: (
43
+ "access denied; querying system processes or services requires an elevated shell"
44
+ ),
45
+ ERROR_BAD_ARGUMENTS: "invalid path; the Restart Manager requires a full file path",
46
+ }
47
+
48
+
49
+ class LockQueryError(OSError):
50
+ """查询失败,例如权限不足或路径非法。"""
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class LockHolder:
55
+ """占用目标文件的一个进程。"""
56
+
57
+ pid: int
58
+ image: str
59
+ image_path: str
60
+ app_name: str
61
+ service: str
62
+ kind: str
63
+ session_id: int
64
+ restartable: bool
65
+
66
+ def to_dict(self) -> dict:
67
+ return {
68
+ "pid": self.pid,
69
+ "image": self.image,
70
+ "image_path": self.image_path,
71
+ "app_name": self.app_name,
72
+ "service": self.service,
73
+ "type": self.kind,
74
+ "session": self.session_id,
75
+ "restartable": self.restartable,
76
+ }
77
+
78
+
79
+ class _FILETIME(ctypes.Structure):
80
+ _fields_ = [
81
+ ("dwLowDateTime", wintypes.DWORD),
82
+ ("dwHighDateTime", wintypes.DWORD),
83
+ ]
84
+
85
+
86
+ class _RM_UNIQUE_PROCESS(ctypes.Structure):
87
+ _fields_ = [
88
+ ("dwProcessId", wintypes.DWORD),
89
+ ("ProcessStartTime", _FILETIME),
90
+ ]
91
+
92
+
93
+ class _RM_PROCESS_INFO(ctypes.Structure):
94
+ _fields_ = [
95
+ ("Process", _RM_UNIQUE_PROCESS),
96
+ ("strAppName", wintypes.WCHAR * (CCH_RM_MAX_APP_NAME + 1)),
97
+ ("strServiceShortName", wintypes.WCHAR * (CCH_RM_MAX_SVC_NAME + 1)),
98
+ ("ApplicationType", ctypes.c_int),
99
+ ("AppStatus", wintypes.ULONG),
100
+ ("TSSessionId", wintypes.DWORD),
101
+ ("bRestartable", wintypes.BOOL),
102
+ ]
103
+
104
+
105
+ _rm = None
106
+ _kernel32 = None
107
+
108
+
109
+ def _load_rm():
110
+ """惰性加载 rstrtmgr,避免在非 Windows 或仅导入包时就报错。"""
111
+ global _rm
112
+ if _rm is not None:
113
+ return _rm
114
+ if sys.platform != "win32":
115
+ raise OSError("wholocks only supports Windows")
116
+
117
+ rm = ctypes.WinDLL("rstrtmgr")
118
+ rm.RmStartSession.argtypes = [
119
+ ctypes.POINTER(wintypes.DWORD),
120
+ wintypes.DWORD,
121
+ wintypes.LPWSTR,
122
+ ]
123
+ rm.RmStartSession.restype = wintypes.DWORD
124
+ rm.RmRegisterResources.argtypes = [
125
+ wintypes.DWORD,
126
+ wintypes.UINT,
127
+ ctypes.POINTER(wintypes.LPCWSTR),
128
+ wintypes.UINT,
129
+ ctypes.POINTER(_RM_UNIQUE_PROCESS),
130
+ wintypes.UINT,
131
+ ctypes.POINTER(wintypes.LPCWSTR),
132
+ ]
133
+ rm.RmRegisterResources.restype = wintypes.DWORD
134
+ rm.RmGetList.argtypes = [
135
+ wintypes.DWORD,
136
+ ctypes.POINTER(wintypes.UINT),
137
+ ctypes.POINTER(wintypes.UINT),
138
+ ctypes.POINTER(_RM_PROCESS_INFO),
139
+ ctypes.POINTER(wintypes.DWORD),
140
+ ]
141
+ rm.RmGetList.restype = wintypes.DWORD
142
+ rm.RmEndSession.argtypes = [wintypes.DWORD]
143
+ rm.RmEndSession.restype = wintypes.DWORD
144
+
145
+ _rm = rm
146
+ return rm
147
+
148
+
149
+ def _load_kernel32():
150
+ global _kernel32
151
+ if _kernel32 is None:
152
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
153
+ k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
154
+ k32.OpenProcess.restype = wintypes.HANDLE
155
+ k32.QueryFullProcessImageNameW.argtypes = [
156
+ wintypes.HANDLE,
157
+ wintypes.DWORD,
158
+ wintypes.LPWSTR,
159
+ ctypes.POINTER(wintypes.DWORD),
160
+ ]
161
+ k32.QueryFullProcessImageNameW.restype = wintypes.BOOL
162
+ k32.CloseHandle.argtypes = [wintypes.HANDLE]
163
+ k32.CloseHandle.restype = wintypes.BOOL
164
+ _kernel32 = k32
165
+ return _kernel32
166
+
167
+
168
+ def _raise_for(rc: int) -> None:
169
+ message = _ERROR_MESSAGES.get(rc, "Restart Manager returned error code %d" % rc)
170
+ raise LockQueryError(rc, message)
171
+
172
+
173
+ def _process_image(pid: int) -> str:
174
+ """取进程可执行文件完整路径;系统进程或权限不足时返回空串。"""
175
+ if not pid:
176
+ return ""
177
+ k32 = _load_kernel32()
178
+ handle = k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
179
+ if not handle:
180
+ return ""
181
+ try:
182
+ size = wintypes.DWORD(32768)
183
+ buffer = ctypes.create_unicode_buffer(size.value)
184
+ if not k32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)):
185
+ return ""
186
+ return buffer.value
187
+ finally:
188
+ k32.CloseHandle(handle)
189
+
190
+
191
+ def collect_files(
192
+ path: str,
193
+ *,
194
+ deep: bool = True,
195
+ max_files: int = _DEFAULT_MAX_FILES,
196
+ ) -> List[str]:
197
+ """把文件或目录展开成待检测的绝对路径列表(去重、保序)。"""
198
+ target = os.path.abspath(os.fspath(path))
199
+ if os.path.isfile(target):
200
+ return [target]
201
+ if not os.path.isdir(target):
202
+ raise FileNotFoundError("path not found: %s" % path)
203
+
204
+ files: List[str] = []
205
+ if deep:
206
+ for root, _dirs, names in os.walk(target):
207
+ for name in names:
208
+ files.append(os.path.join(root, name))
209
+ if len(files) >= max_files:
210
+ return files
211
+ else:
212
+ with os.scandir(target) as entries:
213
+ for entry in entries:
214
+ if entry.is_file():
215
+ files.append(entry.path)
216
+ if len(files) >= max_files:
217
+ break
218
+ return files
219
+
220
+
221
+ def _read_holders(rm, session: wintypes.DWORD) -> List[LockHolder]:
222
+ needed = wintypes.UINT(0)
223
+ count = wintypes.UINT(0)
224
+ reasons = wintypes.DWORD(0)
225
+ rc = rm.RmGetList(
226
+ session, ctypes.byref(needed), ctypes.byref(count), None, ctypes.byref(reasons)
227
+ )
228
+ if rc == ERROR_SUCCESS:
229
+ return []
230
+ if rc != ERROR_MORE_DATA:
231
+ _raise_for(rc)
232
+ if not needed.value:
233
+ return []
234
+
235
+ infos = (_RM_PROCESS_INFO * needed.value)()
236
+ count = wintypes.UINT(needed.value)
237
+ rc = rm.RmGetList(
238
+ session, ctypes.byref(needed), ctypes.byref(count), infos, ctypes.byref(reasons)
239
+ )
240
+ if rc != ERROR_SUCCESS:
241
+ _raise_for(rc)
242
+
243
+ holders: List[LockHolder] = []
244
+ seen = set()
245
+ for index in range(count.value):
246
+ info = infos[index]
247
+ pid = int(info.Process.dwProcessId)
248
+ service = info.strServiceShortName
249
+ app_name = info.strAppName
250
+ key: Tuple[int, str, str] = (pid, service, app_name)
251
+ if key in seen:
252
+ continue
253
+ seen.add(key)
254
+ image_path = _process_image(pid)
255
+ holders.append(
256
+ LockHolder(
257
+ pid=pid,
258
+ image=os.path.basename(image_path) if image_path else "",
259
+ image_path=image_path,
260
+ app_name=app_name,
261
+ service=service,
262
+ kind=APP_TYPES.get(int(info.ApplicationType), "Unknown"),
263
+ session_id=int(info.TSSessionId),
264
+ restartable=bool(info.bRestartable),
265
+ )
266
+ )
267
+ return holders
268
+
269
+
270
+ def _query(files: Sequence[str]) -> List[LockHolder]:
271
+ rm = _load_rm()
272
+ session = wintypes.DWORD(0)
273
+ key = ctypes.create_unicode_buffer(CCH_RM_SESSION_KEY + 1)
274
+ rc = rm.RmStartSession(ctypes.byref(session), 0, key)
275
+ if rc != ERROR_SUCCESS:
276
+ _raise_for(rc)
277
+
278
+ try:
279
+ for start in range(0, len(files), _REGISTER_BATCH):
280
+ chunk = list(files[start : start + _REGISTER_BATCH])
281
+ array = (wintypes.LPCWSTR * len(chunk))(*chunk)
282
+ rc = rm.RmRegisterResources(session, len(chunk), array, 0, None, 0, None)
283
+ if rc != ERROR_SUCCESS:
284
+ _raise_for(rc)
285
+ return _read_holders(rm, session)
286
+ finally:
287
+ rm.RmEndSession(session)
288
+
289
+
290
+ def who_locks(
291
+ path: str,
292
+ *,
293
+ deep: bool = True,
294
+ max_files: int = _DEFAULT_MAX_FILES,
295
+ ) -> List[LockHolder]:
296
+ """返回占用 ``path`` 的进程列表;未被占用时返回空列表。
297
+
298
+ ``path`` 可以是文件,也可以是目录。目录默认递归展开,
299
+ 最多检测 ``max_files`` 个文件(防止误扫整个盘)。
300
+ """
301
+ files = collect_files(path, deep=deep, max_files=max_files)
302
+ if not files:
303
+ return []
304
+ return _query(files)
File without changes
@@ -0,0 +1,52 @@
1
+ import json
2
+ import os
3
+ import sys
4
+
5
+ import pytest
6
+
7
+ from wholocks.cli import EXIT_ERROR, EXIT_LOCKED, EXIT_OK, main
8
+
9
+ pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="wholocks 仅支持 Windows")
10
+
11
+
12
+ def test_locked_file_exits_with_one(tmp_path, capsys):
13
+ target = tmp_path / "locked.bin"
14
+ with open(target, "wb") as handle:
15
+ handle.write(b"x")
16
+ handle.flush()
17
+ assert main([str(target)]) == EXIT_LOCKED
18
+
19
+ out = capsys.readouterr().out
20
+ assert "PID" in out
21
+ assert str(target) == out.splitlines()[0] or str(target) in out
22
+
23
+
24
+ def test_unlocked_file_exits_with_zero(tmp_path, capsys):
25
+ target = tmp_path / "free.bin"
26
+ target.write_bytes(b"x")
27
+ assert main([str(target)]) == EXIT_OK
28
+ assert "not locked" in capsys.readouterr().out
29
+
30
+
31
+ def test_quiet_prints_nothing_for_unlocked(tmp_path, capsys):
32
+ target = tmp_path / "free.bin"
33
+ target.write_bytes(b"x")
34
+ assert main(["-q", str(target)]) == EXIT_OK
35
+ assert capsys.readouterr().out == ""
36
+
37
+
38
+ def test_json_output_is_parseable(tmp_path, capsys):
39
+ target = tmp_path / "locked.bin"
40
+ with open(target, "wb") as handle:
41
+ handle.write(b"x")
42
+ handle.flush()
43
+ assert main(["--json", str(target)]) == EXIT_LOCKED
44
+ payload = json.loads(capsys.readouterr().out)
45
+
46
+ assert payload["locked"] is True
47
+ assert payload["results"][0]["holders"][0]["pid"] == os.getpid()
48
+
49
+
50
+ def test_missing_path_exits_with_two(tmp_path, capsys):
51
+ assert main([str(tmp_path / "nope.txt")]) == EXIT_ERROR
52
+ assert "error:" in capsys.readouterr().err
@@ -0,0 +1,55 @@
1
+ import os
2
+ import sys
3
+
4
+ import pytest
5
+
6
+ from wholocks import who_locks
7
+ from wholocks.core import collect_files
8
+
9
+
10
+ def test_collect_single_file(tmp_path):
11
+ target = tmp_path / "a.txt"
12
+ target.write_text("x")
13
+ assert collect_files(str(target)) == [os.path.abspath(str(target))]
14
+
15
+
16
+ def test_collect_directory_is_recursive_by_default(tmp_path):
17
+ (tmp_path / "sub").mkdir()
18
+ (tmp_path / "top.txt").write_text("x")
19
+ (tmp_path / "sub" / "nested.txt").write_text("y")
20
+
21
+ found = {os.path.basename(path) for path in collect_files(str(tmp_path))}
22
+ assert found == {"top.txt", "nested.txt"}
23
+
24
+
25
+ def test_collect_directory_can_skip_nested(tmp_path):
26
+ (tmp_path / "sub").mkdir()
27
+ (tmp_path / "top.txt").write_text("x")
28
+ (tmp_path / "sub" / "nested.txt").write_text("y")
29
+
30
+ found = [os.path.basename(path) for path in collect_files(str(tmp_path), deep=False)]
31
+ assert found == ["top.txt"]
32
+
33
+
34
+ def test_collect_respects_max_files(tmp_path):
35
+ for index in range(5):
36
+ (tmp_path / ("f%d.txt" % index)).write_text("x")
37
+ assert len(collect_files(str(tmp_path), max_files=2)) == 2
38
+
39
+
40
+ def test_collect_missing_path_raises(tmp_path):
41
+ with pytest.raises(FileNotFoundError):
42
+ collect_files(str(tmp_path / "nope"))
43
+
44
+
45
+ @pytest.mark.skipif(sys.platform != "win32", reason="wholocks 仅支持 Windows")
46
+ def test_detects_process_holding_a_file(tmp_path):
47
+ target = tmp_path / "locked.bin"
48
+ with open(target, "wb") as handle:
49
+ handle.write(b"x")
50
+ handle.flush()
51
+ holders = who_locks(str(target))
52
+
53
+ pids = {holder.pid for holder in holders}
54
+ assert os.getpid() in pids
55
+ assert who_locks(str(target)) == []