Metadata-Version: 2.4
Name: pyi-doctor
Version: 2.1.0
Summary: Build PyInstaller apps as portable exe + installer (Windows exe also from Linux/macOS, experimental), then check startup, antivirus risk factors and bundled licenses.
Author-email: "Juwon Seo (서주원, OMEGA SYSTEMS)" <seodes105@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/sjw0328/pyi-doctor
Project-URL: Issues, https://github.com/sjw0328/pyi-doctor/issues
Project-URL: Source, https://github.com/sjw0328/pyi-doctor
Project-URL: Changelog, https://github.com/sjw0328/pyi-doctor/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/sjw0328/pyi-doctor#readme
Project-URL: Author, https://github.com/sjw0328
Keywords: pyinstaller,installer,inno-setup,antivirus,false-positive,sbom,windows,packaging,cross-compile,exe
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Build Tools
Classifier: Topic :: System :: Software Distribution
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pyinstaller>=6.0
Requires-Dist: pefile>=2023.2.7
Requires-Dist: tomli>=1.1; python_version < "3.11"
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

# pyi-doctor

[![PyPI](https://img.shields.io/pypi/v/pyi-doctor)](https://pypi.org/project/pyi-doctor/)
[![Python](https://img.shields.io/pypi/pyversions/pyi-doctor)](https://pypi.org/project/pyi-doctor/)
[![Downloads](https://static.pepy.tech/badge/pyi-doctor)](https://pepy.tech/project/pyi-doctor)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)

[한국어 문서 (Korean)](README.ko.md)

**Your PyInstaller exe works on your PC, then Windows Defender calls it a trojan on someone else's. pyi-doctor checks why.**

In one call it builds a portable exe and a setup wizard, test-starts the build outside your Python environment, scores common antivirus false-positive risk factors, and lists the third-party licenses you are redistributing. When the start test finds a missing module or data file, `--fix` adds it and rebuilds. AI coding agents can use it through compact JSON or as an MCP server.

```bash
pip install pyi-doctor
pyi-doctor build main.py        # no config needed: entry, name, icon, window/console mode are guessed
pyi-doctor build --fix --write  # add missing hidden_imports / add_data found by the start test, rebuild, save
pyi-doctor diagnose MyApp.exe
pyi-doctor inspect MyApp.exe    # what the exe bundles, read without running it
pyi-doctor scan MyApp.exe       # VirusTotal result + where to report each false positive
```

```python
from pyi_doctor import Project, build_all

project = Project(entry="main.py", name="MyApp", version="1.0.0", publisher="Me")
report = build_all(project, log=print)
print(report.ok)
```

```
dist/release/
├── MyApp-1.0.0-portable-win64.zip   # onedir build (+ THIRD_PARTY_LICENSES.txt)
├── MyApp-1.0.0-win64.exe            # single-file build (if onefile = true)
├── MyApp-1.0.0-setup.exe            # Inno Setup wizard (Windows + Inno Setup)
├── MyApp-1.0.0.cdx.json             # CycloneDX 1.5 SBOM
├── THIRD_PARTY_LICENSES.txt
├── SHA256SUMS.txt
├── av-submission-notes.txt          # text for false-positive submission forms
├── report.md / report.json
```

## What it does

| Step | What happens |
|---|---|
| Portable build | PyInstaller **onedir** build (default) with `--noupx`, a Windows version resource and your icon. Optional **onefile** build. |
| Installer | Writes an Inno Setup script (fixed AppId for upgrades, per-user install by default, modern wizard, Start menu / optional desktop shortcut, uninstaller, English + Korean and other languages) and compiles it. When Inno Setup is not installed on Windows, the pinned Inno Setup release is downloaded into the cache first (see Requirements). |
| Smoke test | Copies each build to a temp folder and starts it with Python's environment variables and folders removed from the environment. Reports missing modules, data files and DLL errors with hints (e.g. "add 'x' to hidden_imports"). |
| Fix loop | `--fix`: an installed module reported missing goes to `hidden_imports`, a missing bundled file found in the project folder goes to `add_data`, then it rebuilds (up to 4 builds). `--write` saves the additions to `pyproject.toml`. |
| Antivirus diagnosis | Reads the PE file (pure Python) and scores commonly cited risk factors: UPX sections, onefile, missing version resource, no signature, prebuilt bootloader, writable+executable sections, bundled modules that are also common in malicious tools (keyboard hooks, browser cookie access, screen capture), default icon. On Windows it can also scan with the local Microsoft Defender CLI (no remediation). |
| Bundle inspection | Reads the archive inside any PyInstaller exe (Windows, Linux or macOS build) without running it: Python version, entry scripts, bundled modules, binaries, data files, largest parts. `compare` shows what changed between two builds. |
| Licenses + SBOM | Maps bundled modules (from PyInstaller's TOC files) to installed distributions and writes `THIRD_PARTY_LICENSES.txt` (also placed next to the exe and inside the installer) and a CycloneDX SBOM. |
| Signing (optional, experimental) | `--sign`: signs the exe files before the installer is compiled, then the installer, with `signtool` (Windows: .pfx, certificate store or Azure Artifact Signing) or `osslsigncode` (Linux/macOS: .pfx). You bring the certificate. |
| VirusTotal (optional) | `scan` / `--virustotal lookup`: looks up the files by SHA-256 hash and lists which engines flag them, each with its false-positive page. `--upload` sends unknown files. |
| Release folder | Collects the files, writes `SHA256SUMS.txt`, a report and false-positive submission notes. Optional upload to a GitHub release through the GitHub CLI (`gh`). |

Only the onedir build is required to succeed; every other step records its own status, so a missing tool (for example Inno Setup) does not stop the rest.

Tools such as briefcase and pyship focus on shipping an app. pyi-doctor focuses on the problems that tend to show up after shipping a PyInstaller build: "it works on my PC only", "Windows Defender calls it a trojan", and "which licenses am I redistributing?".

## Why this exists

pyi-doctor was built by a student developer in Korea, with the help of AI coding tools, after his own PyInstaller apps kept getting flagged by antivirus software.

## Install

```bash
pip install pyi-doctor
```

Requirements: Python 3.9+, PyInstaller 6+ (installed as a dependency). The installer step needs Windows and [Inno Setup](https://jrsoftware.org/isinfo.php) 6.3 or newer. Inno Setup is not bundled. If no installed copy is found (`PYI_DOCTOR_ISCC`, `PATH`, the default Inno Setup 6/7 folders), `build` downloads the Inno Setup 7.1.1 installer from the official [jrsoftware/issrc GitHub release](https://github.com/jrsoftware/issrc/releases), checks its SHA-256 against a value pinned in pyi-doctor, and runs it in portable, current-user mode (`/VERYSILENT /CURRENTUSER /PORTABLE=1`) into the pyi-doctor cache (`~/.cache/pyi-doctor/inno-setup`, or `PYI_DOCTOR_CACHE`). This needs network access to github.com and about 15 MB; no administrator rights are requested. `--no-inno-download`, `build_all(..., inno_download=False)` or `PYI_DOCTOR_NO_INNO_DOWNLOAD=1` turn it off. Inno Setup is third-party software under its own license; check its terms (including the [commercial-use note](https://jrsoftware.org/isdl.php) on its download page) before you use it. The GitHub upload needs the [GitHub CLI](https://cli.github.com/).

## Zero-config start

No settings are needed for a first build. Without a `[tool.pyi-doctor]` table, pyi-doctor guesses them from the project folder and prints what it guessed:

| Setting | Guessed from |
|---|---|
| `entry` | `main.py`, `app.py`, `__main__.py`, ... or the one script with `if __name__ == "__main__"` |
| `name` | `[project].name`, the script name or the folder name |
| `version` | `[project].version` or `__version__` in the script |
| `console` | `false` if the script (or a script it imports) imports tkinter, customtkinter, PySide/PyQt, wx, pygame, kivy, flet, ... |
| `icon`, `license_file`, `add_data` | an `.ico` in the folder or `assets/`, `LICENSE`, folders such as `assets/`, `data/`, `resources/` |

```bash
pyi-doctor check                 # quick checks before building (seconds), with what to change
pyi-doctor build                 # or: pyi-doctor build main.py / path/to/project
pyi-doctor init --write          # keep the guesses + a new fixed app_id in pyproject.toml
```

`check` looks at PyInstaller, the virtual environment, Inno Setup, the entry script's syntax, the icon (valid `.ico`, 256x256 image), `app_id`, publisher, missing files and cross-build limits. `build` runs the same checks first and stops on problems that would make PyInstaller fail (`--no-check` skips this). At the end it prints a step table, the release files and **Next steps** (for example "add 'x' to hidden_imports" or where to get Inno Setup). Guesses are heuristics; review them before a release.

Typos in settings get a suggestion: `unknown setting 'hiden_imports' (did you mean 'hidden_imports'?)`.

## For AI coding agents

With `--brief` the commands print only what needs action, one line each, and `--json` becomes compact (`diagnose` keeps score, level and factor keys; `check` keeps problems and warnings). Brief mode turns on automatically when an AI coding agent is detected (`AI_AGENT`, `CLAUDECODE`, `CURSOR_AGENT`, `CODEX_SANDBOX`, `GEMINI_CLI`, `AIDER_MODEL`); `PYI_DOCTOR_BRIEF=1` / `0` or `--brief` / `--no-brief` override it.

```
$ pyi-doctor build
guessed: entry=main.py name=demo console=true
FAILED: 8 steps, 1 need attention
FAIL smoke: onedir: failed
release: /work/demo/dist/release (4 files)
next: add 'requests' to hidden_imports (or check that the package is installed in the build environment)
```

On the example above the build output went from 2,155 to 703 characters.

`build --json` prints the result as one JSON object. Each next step is an action with a stable `kind`, the setting `key` and the `value` to apply, so an agent does not have to parse sentences:

```json
{"ok":false,"steps":[{"name":"smoke","status":"failed","message":"onedir: failed"}],
 "actions":[{"kind":"add_hidden_import","text":"add 'pefile' to hidden_imports ...","key":"hidden_imports","value":"pefile","auto":true}],
 "release":"/work/demo/dist/release","report":"/work/demo/dist/release/report.json"}
```

`auto: true` marks the changes that `build --fix` applies by itself. A module that is not installed in the build environment gets `install_package` with the pip name instead (for example `cv2` -> `opencv-python`). `pyi-doctor explain KEY` prints the meaning of any factor, action or check key; `pyi-doctor explain exit-codes` lists the exit codes (0 ok, 1 failed, 2 bad arguments). With `--json`, errors are printed as `{"ok": false, "error": "..."}`.

### MCP server

`pyi-doctor mcp` runs a [Model Context Protocol](https://modelcontextprotocol.io) server on stdin/stdout (no extra dependency). Tools: `check`, `build` (with `fix`, `write`, `target`, `onefile`), `diagnose`, `inspect`, `compare`, `smoke`, `scan` (VirusTotal; hash only unless `upload`), `explain`. They return the same compact JSON as `--brief --json`.

```json
{"mcpServers": {"pyi-doctor": {"command": "pyi-doctor", "args": ["mcp"]}}}
```

For Claude Code: `claude mcp add pyi-doctor -- pyi-doctor mcp`. Relative paths are resolved against the server's working folder; build logs go to stderr. `pyi-doctor quickref` prints a short usage summary so an agent does not need to read this README; the same text is in [llms.txt](llms.txt).

Measured with `examples/hello` (Linux x86_64, Python 3.13, PyInstaller 6.22.3, onedir + onefile; command output only, the agent's own thinking time is not included; tokens estimated at about 4 characters per token):

| Agent workflow | Time | Text the agent reads |
|---|---|---|
| `quickref` + `check` + `build` (brief) | 13.6 s | 1,854 characters (~460 tokens) |
| README + `check` + `build` (full output) | same | 29,271 characters (~7,300 tokens) |

A first build of a one-file script with no settings (`pyi-doctor build`, onedir only) took 5.9 s. Each fix-and-rebuild round adds one more build. Times depend on the machine and the size of the app.

## Build the Windows exe on Linux or macOS (experimental)

PyInstaller does not cross-compile, so a Windows exe normally needs a Windows machine (or Wine). `pyi-doctor build --target win` builds a PyInstaller-format Windows exe on Linux or macOS without Wine:

```bash
pip install pyi-doctor
pyi-doctor build --target win -r requirements.txt
```

```python
from pyi_doctor import Project, build_windows

project = Project(entry="main.py", name="MyApp", version="1.0.0", requirements=["requests"])
onedir = build_windows(project)                  # dist/portable/MyApp/MyApp.exe (+ _internal)
single = build_windows(project, onefile=True)    # dist/onefile/MyApp.exe
```

You get the onedir folder, an optional single-file exe, and an Inno Setup script with relative paths (`dist/MyApp.iss`) that compiles on Windows. For comparison, [pynsist](https://pynsist.readthedocs.io/en/latest/faq.html) also builds on Linux/macOS but produces an installer only.

How it works:

1. Downloads the python.org Windows embeddable package (`python3XY.dll`, stdlib) for the same Python minor version as the build machine, the `win_amd64` PyInstaller wheel of the installed PyInstaller version (Windows bootloader), and `win_amd64` / pure-Python wheels of your requirements (`pip download`, with Windows environment markers). Cached in `~/.cache/pyi-doctor` (`PYI_DOCTOR_CACHE`).
2. Finds modules with PyInstaller's modulegraph against those folders, and DLLs used by `.pyd` files from their PE import tables (`pefile`). PyInstaller hooks are run with replacements that read the unpacked files instead of importing the package.
3. Writes PYZ, `base_library.zip` and the CArchive in PyInstaller's format, adds icon, version information and manifest to the bootloader as PE resources (pure Python), and sets the PE checksum.
4. Runs the antivirus risk-factor diagnosis on the result. It does not start the exe; [examples/github-actions/cross-build-windows.yml](examples/github-actions/cross-build-windows.yml) builds on `ubuntu-latest` and starts the exe on `windows-latest`.

Scope. The build stops before writing files, with a list of reasons, when any of these apply:

- target other than 64-bit Windows (x64); no 32-bit or ARM64
- a requirement without a pure-Python or `win_amd64` wheel for your Python version on PyPI
- a PyInstaller hook that needs to import the package, defines `hook(hook_api)`, or calls a helper that cannot be answered from files
- tkinter (and so customtkinter): the embeddable package has no Tcl/Tk
- a DLL needed by a `.pyd` that is neither in the wheels nor a known Windows system DLL

Checked on Linux with Python 3.13 (the end-to-end test also passes on 3.12): stdlib (ssl, sqlite3, ctypes), requests, PyYAML (C extension), click, rich, tqdm, colorama, charset-normalizer (mypyc), Pillow, pydantic 2 (Rust extension), psutil, orjson and pywin32 built and ran under Wine 9 in onedir and onefile mode; numpy built, but could not be run under Wine 9. Other packages are untested. Results on real Windows can differ, so start the exe on Windows before distributing it.

Settings: `requirements` (defaults to `[project].dependencies`), `-r FILE`, `--python-version X.Y.Z` (must match the build Python's X.Y). `pyinstaller_args` and PNG icons are not supported by the cross build.

## VirusTotal and false-positive reports

```bash
export VT_API_KEY=...                       # free key from your VirusTotal account
pyi-doctor scan dist/release/MyApp-1.0.0-setup.exe
pyi-doctor scan MyApp.exe --upload          # send the file when VirusTotal does not know its hash
pyi-doctor build --virustotal lookup        # also as a build step; detections go into av-submission-notes.txt
```

```
MyApp.exe: 2/72 engines flag it  (https://www.virustotal.com/gui/file/...)
  - Microsoft: Trojan:Win32/Wacatac.B!ml
    false positive: https://www.microsoft.com/en-us/wdsi/filesubmission
  - SomeEngine: Gen.Python
    false positive: https://docs.virustotal.com/docs/false-positive-contacts
```

Without `--upload` only the SHA-256 hash is sent. A freshly built file is usually unknown to VirusTotal, so a first check needs `--upload`. **Uploaded files are shared by VirusTotal with its partners**; do not upload software you want to keep private. The public API allows 4 requests per minute. Results come from third-party engines and change over time; a clean result does not mean that a file is safe or will not be flagged later. The false-positive pages come from VirusTotal's contact list; submitting is up to you. `--fail-on-detection` makes `scan` exit with 1 when any engine flags a file (for CI).

## Signing (experimental)

```bash
export PYI_DOCTOR_SIGN_PASSWORD=...                     # .pfx password (never on the command line)
pyi-doctor build --sign --sign-pfx cert.pfx             # Windows: signtool; Linux/macOS: osslsigncode
pyi-doctor build --sign --sign-thumbprint 1A2B...       # Windows certificate store
pyi-doctor build --sign --sign-dlib Azure.CodeSigning.Dlib.dll --sign-metadata metadata.json  # Azure Artifact Signing
pyi-doctor sign MyApp.exe --sign-pfx cert.pfx           # sign existing files
```

The same settings can come from `PYI_DOCTOR_SIGN_PFX`, `PYI_DOCTOR_SIGN_THUMBPRINT`, `PYI_DOCTOR_SIGN_DLIB`, `PYI_DOCTOR_SIGN_METADATA` and `PYI_DOCTOR_SIGN_TIMESTAMP` (default `http://timestamp.digicert.com`; `none` turns timestamping off). pyi-doctor only runs the signing tool: it does not provide certificates, and a signature does not guarantee that antivirus products accept a file. In `build`, the exe files are signed before the installer is compiled, so the installer carries signed files; the installer is signed afterwards. A file counts as signed when the tool succeeds and the exe contains a signature. With signtool and a .pfx, the password is passed as `/p` and is visible to other processes on the same machine while signtool runs; it is removed from pyi-doctor's own output.

## Inspect and compare builds

```bash
pyi-doctor inspect dist/portable/MyApp        # onedir folder or exe; also onefile exe files
pyi-doctor compare old/MyApp.exe new/MyApp.exe
```

```
dist/portable/xb/xb.exe
  layout: onedir, Python 3.13 (python313.dll), total 18.3 MB in 29 file(s)
  entry scripts: main
  modules: 199 (85 top-level), binaries: 17, data files: 11
  largest:
    python313.dll                               5.9 MB  (1 files)
    libcrypto-3.dll                             5.7 MB  (1 files)
  modules also common in malicious tools (scanners may weigh them):
    pynput: keyboard/mouse hooks
```

`inspect` reads the CArchive appended to the exe and the module list of its PYZ archive with the standard library only; nothing is executed or imported, so it also works on a Windows exe from Linux or macOS. For onefile builds sizes are uncompressed. It lists large packages that are often bundled by accident (Qt, NumPy, pandas, Tcl/Tk, ...) so they can go to `excludes` if the app does not use them. `compare` reports size and risk score changes and the modules, binaries and risk factors added or removed, which helps to spot a dependency update that pulled in something new before a release.

```python
from pyi_doctor import inspect_bundle, compare_builds

b = inspect_bundle("dist/onefile/MyApp.exe")    # Bundle(python, modules, binaries, datas, largest, sensitive, ...)
diff = compare_builds("v1/MyApp.exe", "v2/MyApp.exe")
```

## Configuration

Add a table to your `pyproject.toml` (`pyi-doctor init --write` adds a template):

```toml
[tool.pyi-doctor]
entry = "main.py"
name = "MyApp"
version = "1.0.0"
publisher = "Your Name"
description = "What the app does"
icon = "assets/app.ico"
app_id = "PUT-A-FIXED-GUID-HERE"   # keep it fixed after the first release
console = false
onefile = false
license_file = "LICENSE"            # shown in the installer
add_data = ["assets=assets"]
hidden_imports = []
languages = ["english", "korean"]
```

`name`, `version` and `description` fall back to `[project]`. If `app_id` is not set, a GUID is derived from publisher and name; changing either then changes the GUID, so set it explicitly before the first release.

<details>
<summary>All settings</summary>

| Key | Default | Meaning |
|---|---|---|
| `entry` | required | Script PyInstaller starts from |
| `name` | required | Exe name (also the default for the two keys below) |
| `display_name` | `name` | Name shown in the installer, Start menu, install folder and Apps list |
| `installer_name` | `{name}-{version}-setup` | Installer file name; may use `{name}`, `{version}`, `{display_name}` |
| `version` | `0.1.0` | Version string; the first four numbers go into Windows version resources |
| `publisher`, `description`, `copyright`, `website` | `""` | Metadata for version resources, installer and reports |
| `icon` | none | `.ico` file |
| `app_id` | derived | Installer AppId: a GUID, or the existing non-GUID AppId of an app already released with another Inno Setup script |
| `console` | `false` | `true` for command-line apps |
| `onefile` | `false` | Also build a single-file exe |
| `upx` | `false` | Allow UPX (adds a high-weight risk factor) |
| `hidden_imports`, `excludes` | `[]` | Passed to PyInstaller |
| `add_data` | `[]` | `"src=dest"`, `"src;dest"` or `["src", "dest"]` |
| `pyinstaller_args` | `[]` | Extra PyInstaller arguments |
| `license_file` | none | License page in the installer |
| `privileges` | `lowest` | `lowest` (per-user, can be raised in the wizard) or `admin` |
| `languages` | `["english", "korean"]` | Installer languages available in your Inno Setup |
| `smoke_args`, `smoke_timeout` | `[]`, `15` | Arguments and seconds for the smoke test |
| `requirements` | `[project].dependencies` | `--target win` only: requirement strings or `"-r file.txt"` for the Windows wheels |
| `output_dir`, `work_dir` | `dist`, `build` | Output folders |

</details>

## Desktop window (GUI)

```bash
pip install pyi-doctor
pyi-doctor            # without arguments the window opens (also: pyi-doctor gui, pyi-doctor-gui)
pyi-doctor shortcut   # optional: put a shortcut on the desktop, then open it with a double-click
```

Without arguments the window opens when a screen is available; in AI-agent environments and without a display the usual help is printed instead. `shortcut` writes `pyi-doctor.lnk` on the Windows desktop (no console window), an app-menu entry on Linux, or `pyi-doctor.command` on the macOS desktop, for the current user only. The window also has an *Add desktop shortcut* button.

A tkinter window with three tabs.

**Easy** (opens first, English or Korean by system language; the button at the top right switches): choose a `.py` file or folder, check the settings (program name, icon, version, made by, window/console type), press *Make my program*. *Choose icon...* takes an `.ico`, `.png` or `.jpg` and makes an `.ico` in the project folder (a square PNG up to 256x256 works without extra packages; other pictures need Pillow, which the window can install). *Save settings* keeps the settings in `pyproject.toml` with a fixed `app_id` so later versions upgrade the installed one. The quick checks run first; missing modules and data files reported by the start test are added and the app is rebuilt (up to 3 builds); when a package is missing on the computer, a button installs it with pip into the Python that runs pyi-doctor and builds again. The result is shown in plain words: which files to share (installer, portable zip, single exe), the antivirus risk level and what to do next.

![Easy tab](https://raw.githubusercontent.com/sjw0328/pyi-doctor/main/docs/gui-easy-en.png)

**Advanced**: every setting. *Open project folder...* (or `pyi-doctor gui path/to/project`) fills the form, guessing missing settings; picking an entry script fills empty fields (name, version, icon, console). Tick the steps and press *Build*; the log shows each step, then the summary with next steps. *Check* runs the quick checks, *Save settings* writes a `[tool.pyi-doctor]` block with a new fixed `app_id`, *Open output folder* / *Open report* open the results, and the last form is restored on the next start. **Diagnose**: pick any `.exe` and see its risk factors. All tabs run the same `build_all()` / `diagnose()` as the command line. tkinter ships with the python.org installers for Windows and macOS; on Debian/Ubuntu install `python3-tk`. The plain-language texts are simplified; *Show details* opens the full log.

## Command line

```bash
pyi-doctor build                        # full pipeline (pyproject.toml, or guessed settings)
pyi-doctor build main.py --icon app.ico --publisher "Me" --open
pyi-doctor check                        # quick checks before building
pyi-doctor quickref                     # short usage summary (for AI agents)
pyi-doctor build --onefile --no-defender
pyi-doctor build --github-release v1.0.0 --github-repo me/myapp
pyi-doctor build --target win -r requirements.txt   # Windows exe from Linux/macOS (experimental)
pyi-doctor build --fix --write          # add missing hidden imports / data files, rebuild, save them
pyi-doctor build --json                 # result + structured actions as JSON
pyi-doctor diagnose dist/portable/MyApp/MyApp.exe   # score any exe
pyi-doctor inspect dist/portable/MyApp  # bundled modules, binaries, sizes
pyi-doctor compare old.exe new.exe      # what changed between two builds
pyi-doctor scan MyApp.exe [--upload]    # VirusTotal result (VT_API_KEY)
pyi-doctor sign MyApp.exe --sign-pfx cert.pfx   # Authenticode signing (experimental)
pyi-doctor build --sign --virustotal lookup     # sign + VirusTotal as build steps
pyi-doctor explain stock_bootloader     # meaning of a factor, action or check key
pyi-doctor mcp                          # MCP server for AI agents
pyi-doctor diagnose MyApp.exe --no-icon             # also count the default-icon factor
pyi-doctor smoke dist/portable/MyApp/MyApp.exe -- --version
pyi-doctor iss                          # write the Inno Setup script only
pyi-doctor init --write                 # add [tool.pyi-doctor] (guessed values + new app_id) to pyproject.toml
pyi-doctor gui                          # open the desktop window (or just: pyi-doctor)
pyi-doctor shortcut                     # desktop shortcut that opens the window
pyi-doctor icon logo.png                # make logo.ico (PNG without extra packages; JPG etc. with Pillow)
```

## Library API

```python
from pyi_doctor import Project, build_portable, build_installer, smoke_test, diagnose, collect_licenses, check, detect
from pyi_doctor.installer import ensure_iscc

project = Project.load(".")                          # pyproject.toml, or guessed settings (see project.detected)
onedir = build_portable(project)                     # Artifact(kind="onedir", path=..., folder=...)
result = smoke_test(onedir.path, timeout=10)         # SmokeResult(ok, status, missing_modules, ...)
risk = diagnose(onedir.path, icon_configured=True)   # Diagnosis(score, level, factors, defender, ...)
setup = build_installer(project, onedir.folder)      # Windows; downloads Inno Setup if missing
iscc = ensure_iscc()                                 # path to ISCC.exe (installed or downloaded)
packages, mode = collect_licenses(project.work_path / "onedir")
```

```python
from pyi_doctor import build_with_fixes, actions_for, inspect_bundle, compare_builds

report, fixes = build_with_fixes(project, rounds=4)  # fixes: [Action(kind, text, key, value, auto)]
for a in actions_for(report, project):
    print(a.kind, a.key, a.value, a.text)
```

```python
from pyi_doctor import scan_virustotal, sign_files
from pyi_doctor.signing import SignConfig

vt = scan_virustotal("MyApp.exe")                     # ScanResult(status, flagged, engines, detections, link)
res = sign_files(["MyApp.exe"], SignConfig(pfx="cert.pfx"))   # [SignResult(path, ok, message)]
```

`check(project)` returns the quick checks (`name`, `status`, `message`, `fix`); `detect(folder)` returns the guessed settings without building.

`build_all(project, onefile=..., installer=..., smoke_test=..., diagnose=..., defender=..., licenses=..., sbom_file=..., github_tag=..., target="win", sign=SignConfig(...), virustotal="lookup")` runs everything and returns a `Report` with `.ok`, `.steps`, `.to_markdown()` and `.to_json()`.

## About the antivirus score

The score adds fixed weights for factors that are commonly reported to affect heuristic detection of PyInstaller executables (UPX 30, onefile 20, no version resource 15, unsigned 15, prebuilt bootloader 10, writable+executable section 10, modules also common in malicious tools 10, default icon 5). The module factor lists modules such as `pynput`, `keyboard`, `browser_cookie3`, `win32crypt` and `mss`; legitimate apps use them too, and the factor only says that a scanner may weigh them. It is meant for comparing your own builds. It does not predict the verdict of Microsoft Defender or any other product, and a low score does not mean a file will not be flagged.

pyi-doctor does not obfuscate, encrypt or otherwise hide code from scanners. It applies ordinary distribution practices (version information, no packer, onedir layout, signing advice) and helps you prepare a false-positive report. Code signing with a certificate from a trusted authority is generally the most effective measure; `--sign` runs the signing tool with your certificate, but obtaining a certificate is outside the scope of this tool.

## Measured on the bundled example

`examples/hello`, Linux x86_64, Python 3.13, PyInstaller 6.22.3 (installer step skipped because it needs Windows):

| Step | Time |
|---|---|
| onedir build | 4.5 s |
| onefile build | 12.2 s |
| licenses + SBOM | 0.8 s |
| smoke test (both builds) | 0.6 s |
| diagnosis | < 0.1 s |
| release folder (zip + checksums) | 1.5 s |
| **total** | **19.7 s** |

Test suite: 282 tests (including 3 real PyInstaller builds, 2 cross builds and an Inno Setup download on Windows) on Linux; CI runs the unit tests on Python 3.9–3.14 on Linux and Windows, and the cross build on Linux with a start test on Windows. Windows-specific paths (version resource, Inno Setup compilation, Defender scan, error-dialog detection in the smoke test) run in the Windows CI jobs.

## Known limitations

- Windows features (installer, version resource, Defender scan) need Windows. On other systems the `.iss` script is still written.
- The smoke test is a heuristic. It removes Python from the environment but does not reproduce a clean PC (installed DLLs, Visual C++ runtime, fonts, etc.). GUI apps that keep running are counted as started. Windowed apps that crash show a PyInstaller error dialog; on Windows pyi-doctor looks for that dialog by window title, which may not catch every case.
- The bootloader check compares the exe's code section (`.text`) with stock PyInstaller Windows bootloaders found on this machine: the installed PyInstaller (on Windows) and the `win_amd64` wheels cached by `--target win`. An exe made with a PyInstaller version that is not present is reported as `unknown` and not scored.
- License notices come from package metadata, which can be missing or wrong; packages loaded dynamically may be missed. Review the generated file.
- Guessed settings and the quick checks are heuristics based on file names and imports; they can be wrong or miss problems.
- `--fix` only adds `hidden_imports` (modules installed in the build environment) and `add_data` (files found in the project folder) based on error messages from the start test; it does not edit code. A file opened relative to the working folder is reported but not fixed automatically. Review the added settings.
- `inspect` reads archives of PyInstaller 4.x-6.x; other layouts are reported as not readable. The list of modules also common in malicious tools is short and fixed; its absence says nothing about how a scanner will judge the file.
- Only PyInstaller is supported (no Nuitka / cx_Freeze). No auto-update.
- Signing is experimental: tested with osslsigncode and a self-signed certificate; signtool and Azure Artifact Signing are passed through as documented by Microsoft and depend on your certificate setup.
- VirusTotal lookups depend on a third-party service, its API limits and terms; results can change after the build.
- The Windows cross build (`--target win`) is experimental: it covers only the scope listed above, is not checked against every PyInstaller hook, and does not start the exe. Downloads from python.org and PyPI are not signature-checked beyond HTTPS.

## Disclaimer

pyi-doctor is rule-based and may miss problems or report problems that do not exist. Its reports are informational and do not replace your own testing, review of licenses, or obligations under applicable law; checking the results and complying with license terms and laws remain the user's responsibility. The software is provided "AS IS", without warranty of any kind, under the MIT License.

pyi-doctor is an independent project and is not affiliated with or endorsed by the PyInstaller project, Jordan Russell / Inno Setup, Microsoft, GitHub, VirusTotal or any antivirus vendor. Product names are trademarks of their respective owners.

## License

MIT © 2026 [Juwon Seo](https://github.com/sjw0328) (서주원, OMEGA SYSTEMS) · Contact: seodes105@gmail.com
