Check Python library compatibility with HarmonyOS. Downloads source from GitHub/PyPI, detects Windows-specific dependencies, runs pytest with per-test-case r...
---
name: python-harmony-compatibility-checker
description: Check Python library compatibility with HarmonyOS. Downloads source from GitHub/PyPI, detects Windows-specific dependencies, runs pytest with per-test-case reporting, and generates detailed compatibility reports.
---
# Python HarmonyOS Compatibility Checker
## When to Use
- Check if a Python package works on HarmonyOS
- Validate multiple packages before deployment
- Migrate a Python project to HarmonyOS
- Detect Windows-specific API dependencies (win32api, pythoncom, pywin32, etc.)
## Usage
```bash
# Single package
python scripts/check_compatibility.py requests
# Multiple packages (parallel, 4 workers default)
python scripts/check_compatibility.py requests numpy pandas flask
# Specify workers
python scripts/check_compatibility.py --workers 8 requests numpy pandas
# From requirements file
python scripts/check_compatibility.py -r requirements.txt
python scripts/check_compatibility.py -w 8 -r requirements.txt
# Sequential mode (debugging)
python scripts/check_compatibility.py --sequential requests numpy
# Keep downloaded source for verification
python scripts/check_compatibility.py --keep-source numpy
```
### Options
| Option | Description | Default |
|--------|-------------|---------|
| `-w, --workers N` | Number of parallel workers | 4 |
| `--sequential` | Run checks one at a time | False |
| `-r, --requirements FILE` | Check packages from requirements file | - |
| `--keep-source` | Keep downloaded source code for verification | False |
## Output
Reports saved to current directory:
- `compatibility_report_*.md` - Markdown with summary and details
- `compatibility_report_*.json` - Machine-readable with per-test-case results
Timestamps use **东八区时间 (UTC+8/北京时间)**.
### Example (numpy)
```
📦 numpy v2.2.1
Status: ✅ Compatible
Test Pass Rate: 88.9%
Total: 45 tests | Passed: 40 | Failed: 5
```
### Metrics
| Metric | Description |
|--------|-------------|
| **Total Tests** | Individual test functions run |
| **Passed** | Successfully completed |
| **Failed** | Failed due to code issues |
| **Environment Issues** | Permission/temp dir failures (not counted) |
| **Pass Rate** | `passed / total` |
| **Valid Pass Rate** | `passed / (passed + failed)` - excludes environment issues |
## Test Workflow
1. **Download Source** - GitHub (preferred) or PyPI
2. **Windows Check** - Scan for Windows-specific imports (win32api, pythoncom, pywin32, ctypes.windll)
- Found → **Incompatible** (no further testing)
3. **Find Tests** - From installed package (preferred) or source
4. **Run Tests** - pytest with verbose output, per-function reporting
5. **Analyze** - Categorize: environment issues vs code issues
6. **Report** - Markdown + JSON with detailed results
### Status
| Status | Criteria |
|--------|----------|
| **✅ Compatible** | Installs + valid pass rate ≥ 80% + no Windows deps |
| **⚠️ Partial** | Installs + valid pass rate 50-79% |
| **❌ Incompatible** | Cannot install OR valid pass rate < 50% OR Windows deps detected |
### Error Classification
| Type | Description | Counts Against |
|------|-------------|----------------|
| **Environment** | Permission errors, temp dir issues | ❌ No |
| **Code** | Import errors, API incompatibilities | ✅ Yes |
| **Platform** | Windows/macOS/X11 dependencies | ✅ Yes |
## Known Issues
### Platform Dependencies
| Platform | Problematic Packages | Alternative |
|----------|---------------------|-------------|
| Windows | pywin32, wmi, pythoncom, **xlwings** | Cross-platform libs |
| macOS | applescript, quartz, cocoa | - |
| X11 | python-xlib, xcb | pynput |
### Windows Module Detection
Scans for: `win32api`, `win32con`, `win32gui`, `win32com`, `pythoncom`, `pywintypes`, `ctypes.windll`, `winsound`, `msvcrt`
**Detection includes:**
- Direct imports: `import win32api`, `from win32com import ...`
- Dynamic imports: `importlib.import_module('pythoncom')`
- ctypes Windows DLL: `ctypes.windll`, `ctypes.WinDLL`
- References in setup.py, pyproject.toml
### Compatible Packages
- `requests`, `numpy` (45 tests, 88.9%), `pandas`, `flask`, `django`, `pytest`, `beautifulsoup4`, `pillow`
## Scripts
### check_compatibility.py
**Features:**
- Source download from GitHub/PyPI
- Windows dependency detection
- Test discovery from installed package or source
- pytest integration with per-test-case reporting
- Environment issue detection
- Source code retention (`--keep-source`)
**pytest Integration:**
- Uses `pytest -v --tb=short --import-mode=importlib`
- Runs from `/tmp` to avoid source import conflicts
- Parses output for individual test function results
- Limits to 15 test files, shows progress every 5 files
## Troubleshooting
### Permission Errors
```bash
# Clean up pytest temp directories
rm -rf pytest-of-*
```
### Source Verification
```bash
# Keep source for inspection
python scripts/check_compatibility.py --keep-source xlwings
# Check Windows imports
grep -r "import win32" /path/to/source/
```
### False Positives
Some failures may be due to:
- Missing optional system libraries
- Network-dependent tests
- pytest configuration issues
Review detailed reports to distinguish real incompatibilities from environment issues.
## Integration
### CI/CD
```yaml
- name: HarmonyOS Compatibility
run: python scripts/check_compatibility.py -r requirements.txt --keep-source
```
### Programmatic
```python
from scripts.check_compatibility import check_package
result = check_package("requests")
print(f"Compatible: {result.compatible}, Issues: {result.issues}")
```
## Limitations
- Binary dependencies may fail to compile
- Some packages require system-level dependencies
- Pure HarmonyOS (NEXT) has stricter security policies
- Not all packages have unit tests
- Network required for source download
## Related
- `references/python-env-setup.md` - Python setup on HarmonyOS
- `references/compatibility-database.md` - Known package status
## Best Practices
### For Users
1. Review error classifications (environment vs code)
2. Use `--keep-source` to verify tested code
3. Run multiple times for transient failures
4. Check Windows dependencies first
### For Authors
1. Include tests in your package
2. Use pytest
3. Avoid platform-specific tests (or use `@pytest.mark.skipif`)
4. Document system dependencies
5. Use conditional imports: `if sys.platform == 'win32'`
don't have the plugin yet? install it then click "run inline in claude" again.
added explicit inputs section with parameter and environment details, broke procedure into 10 numbered steps with clear input/output for each, extracted implicit decision logic into separate decision points section covering download failure, windows deps, install errors, missing tests, timeouts, and rate limiting, formalized output contract with markdown and json file schemas, and documented edge cases including rate limits, auth expiry, empty results, and pytest conflicts.
this skill validates whether Python packages work on HarmonyOS by downloading source code, scanning for Windows-specific dependencies, running the package's test suite via pytest, and generating detailed compatibility reports. use it before deploying Python libraries to HarmonyOS, migrating projects to HarmonyOS, or validating multiple packages in batch.
command-line parameters:
package_names (positional args): one or more Python package names to check-w, --workers N (optional): number of parallel workers for batch checks, default 4--sequential (optional flag): run checks one at a time instead of in parallel, useful for debugging-r, --requirements FILE (optional): path to requirements.txt file, check all packages listed--keep-source (optional flag): retain downloaded source code in /tmp for manual inspectionexternal dependencies:
/tmp directory with at least 500MB free space per concurrent workerenvironment context:
parse input: read package names from command line args, -r requirements.txt file, or -w/--workers count. validate package names are non-empty strings. if both positional args and -r flag provided, combine both lists.
output: list of package names, worker count (1 if --sequential), boolean flags for --keep-source
download source code: for each package, attempt GitHub source repo first (via git clone or API), fallback to PyPI source tarball (pip download --no-binary :all__ or direct PyPI fetch). save to /tmp/harmony_check_{package}_{timestamp}. if download fails, record error and skip to step 8 (report incompatible).
output: local directory path containing source, or null if download failed
scan for Windows-specific dependencies: parse source files (*.py, setup.py, pyproject.toml) with regex patterns for these imports: win32api, win32con, win32gui, win32com, pythoncom, pywintypes, ctypes.windll, ctypes.WinDLL, winsound, msvcrt. also check dynamic imports via importlib.import_module('win32*') or string literals. if any detected, mark package incompatible and skip to step 8.
output: list of detected Windows dependencies (empty if none found)
install package: run pip install {package} in isolated environment or current venv. if installation fails (missing binary, unmet dependencies), record error, skip to step 8 (mark incompatible).
output: installed package path, or error message
discover test suite: attempt to locate pytest test files in installed package site-packages first (look for test_*.py or *_test.py in package root and tests/ subdirectory). if not found, search source directory from step 2. if no tests found, record warning but continue with empty test count (0 total tests, 0 passed, pass rate undefined).
output: list of test file paths (may be empty)
run pytest: execute pytest -v --tb=short --import-mode=importlib {test_files} from a temporary working directory (/tmp/pytest_run_{timestamp}) to isolate imports. capture stdout and stderr. set 15-file limit and show progress every 5 files. parse output line-by-line for individual test results (PASSED, FAILED, ERROR, SKIPPED).
output: raw pytest output, list of individual test results with status (passed/failed/error/skipped), error messages
classify failures: for each failed or error test, examine error message. categorize as: (a) environment issue (permission denied, cannot write to temp dir, file not found in /tmp), (b) code issue (ImportError, AttributeError, AssertionError, test logic failure), (c) platform issue (Windows API call, macOS-specific, X11 reference). count each category.
output: pass count, fail count, environment issue count, code issue count, platform issue count
calculate status: compute metrics:
output: status (compatible/partial/incompatible), pass rate percentage, metric counts
generate reports: write two files to current working directory:
compatibility_report_{package}_{timestamp}.md: human-readable markdown with package name, version, status, summary metrics, per-test results, detected Windows deps, and recommendationscompatibility_report_{package}_{timestamp}.json: machine-readable JSON with package, version, status, total_tests, passed, failed, environment_issues, code_issues, platform_issues, pass_rate, windows_deps, test_details (array of {name, status, error_message})output: file paths created
cleanup: if --keep-source flag not set, delete /tmp/harmony_check_{package}_{timestamp} directory. always delete /tmp/pytest_run_{timestamp} after report generation.
output: none (side effect: disk cleanup)
if download fails (step 2): mark package incompatible, record download error in report, skip to step 8. do not attempt install or testing.
if Windows dependencies detected (step 3): immediately mark incompatible, skip steps 4-7, jump to step 8. no further testing needed.
if package installation fails (step 4): mark incompatible, record install error, skip steps 5-6, jump to step 8.
if no test files found (step 5): log warning, continue to step 6 with empty test list. pytest will run with no test discovery and return 0 tests. final metrics will show 0 total, 0 passed, undefined pass rate. mark as incompatible due to insufficient test coverage data (cannot validate).
if pytest execution times out (step 6): after 5 minutes per package, kill process, record timeout error, treat as code failure. count timeout as 1 failed test.
if valid pass rate cannot be calculated (zero denominator in step 8): assign pass_rate as null, status as incompatible (insufficient data).
if environment issue count > 0 (step 7): exclude these from total test count when computing valid pass rate. report environment issues separately from code issues in output so user can distinguish transient failures from real incompatibilities.
if running in parallel mode with worker failures: if a single worker crashes, log error and continue with other workers. collect all results and merge into single summary report or separate per-package reports depending on batch size.
file locations:
compatibility_report_{package_name}_{YYYYMMDD_HHMMSS_UTC+8}.md (markdown report)compatibility_report_{package_name}_{YYYYMMDD_HHMMSS_UTC+8}.json (json report)both files written to current working directory (pwd).
markdown format:
# Compatibility Report: {package} v{version}
## Status
✅ Compatible | ⚠️ Partial | ❌ Incompatible
## Summary
- Pass Rate: X%
- Total Tests: N | Passed: M | Failed: K
- Valid Pass Rate: Y% (excludes environment issues)
- Windows Dependencies: [list or none]
## Test Results
[table or list of individual test outcomes]
## Environment Issues
[list of permission/temp dir errors if any]
## Recommendations
[actionable next steps based on failures]
json format:
{
"package": "string",
"version": "string",
"status": "compatible|partial|incompatible",
"timestamp": "ISO8601_UTC+8",
"metrics": {
"total_tests": integer,
"passed": integer,
"failed": integer,
"environment_issues": integer,
"code_issues": integer,
"platform_issues": integer,
"pass_rate_percent": float or null
},
"windows_dependencies": [array of strings],
"install_error": "string or null",
"download_error": "string or null",
"test_details": [
{
"test_name": "string",
"status": "PASSED|FAILED|ERROR|SKIPPED",
"error_message": "string or null",
"issue_type": "environment|code|platform|none"
}
]
}
skill succeeded if:
.md file and see status, metrics, and test breakdownskill failed if:
user can verify by:
ls -la compatibility_report_*.{md,json} in current directorycat compatibility_report_*.md to read human summaryjq . compatibility_report_*.json to validate json and inspect metricsrate limiting: PyPI and GitHub may rate-limit large batch requests. if downloading 50+ packages in parallel with --workers 8, expect 429 errors on some packages. retry with --sequential or reduce worker count to 2-4.
auth expiry: if GitHub API token in env var expires mid-batch, subsequent downloads from private repos will fail. manually refresh token and re-run.
empty result sets: packages with zero tests will have pass_rate as null and status incompatible (no data to validate). this is correct behavior, not a failure.
network timeouts: source downloads may timeout on slow networks. default timeout 30 seconds per package. if behind corporate proxy, may need to configure pip with pip config set global.index-url https://....
pytest config conflicts: if package's pytest.ini conflicts with system pytest, use --import-mode=importlib to isolate. some packages may still fail due to fixture incompatibilities.
binary compilation failures: packages with C extensions (numpy, pandas) may fail to install if gcc/clang missing. error will be caught in step 4 and marked incompatible.
transient test failures: some tests pass/fail non-deterministically (network calls, file timing). run with multiple instances or use --sequential for stable baseline.
Windows module false positives: dynamic imports like getattr(module, 'win32api') may not be detected. always review --keep-source output manually for edge cases.