Install & Compatibility
Where this runs
tested against v0.45.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
build_error
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 1.8s · import 0.000s · 19MB
16MB installed
● package 16MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
main
✓ from ast_grep_cli import main
✗ from ast_grep_cli import main
This quickstart demonstrates how to use `ast-grep-cli` from Python by invoking the `sg` command via `subprocess.run()`. It shows both a search operation with JSON output and a dry-run rewrite example. Always prefer using `--json` output for robust parsing of `ast-grep` results in scripts.
import subprocess
import os
import json
# Create a dummy file for demonstration
dummy_js_code = """
function greet(name) {
console.log("Hello, " + name);
}
greet("World");
"""
with open("example.js", "w") as f:
f.write(dummy_js_code)
try:
# Example 1: Search for 'console.log($$$)' pattern and get JSON output
print("--- Searching for console.log statements (JSON output) ---")
command_search = [
"sg",
"run",
"--pattern",
"console.log($$$)",
"--lang",
"javascript",
"--path",
"example.js",
"--json" # Use JSON output for programmatic parsing
]
search_result = subprocess.run(
command_search,
capture_output=True,
text=True,
check=False # Do not raise CalledProcessError if no matches (returns non-zero exit code)
)
print(f"Search Exit Code: {search_result.returncode}")
if search_result.stdout:
try:
json_output = json.loads(search_result.stdout)
print("Parsed JSON Output:", json.dumps(json_output, indent=2))
except json.JSONDecodeError:
print("Stdout (not valid JSON):", search_result.stdout)
if search_result.stderr:
print(f"Search Stderr:\n{search_result.stderr}")
# Example 2: Perform a dry-run rewrite from 'console.log' to 'alert'
print("\n--- Performing a dry-run rewrite (stdout output) ---")
command_rewrite_dry_run = [
"sg",
"run",
"--pattern",
"console.log($$$)",
"--rewrite",
"alert($$$)",
"--lang",
"javascript",
"--path",
"example.js",
"--dry-run" # Show changes without modifying the file
]
rewrite_result = subprocess.run(
command_rewrite_dry_run,
capture_output=True,
text=True,
check=False
)
print(f"Rewrite Dry-Run Exit Code: {rewrite_result.returncode}")
print(f"Rewrite Dry-Run Stdout:\n{rewrite_result.stdout}")
if rewrite_result.stderr:
print(f"Rewrite Dry-Run Stderr:\n{rewrite_result.stderr}")
except FileNotFoundError:
print("Error: 'sg' command not found. Ensure ast-grep-cli is installed and in your PATH.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
if os.path.exists("example.js"):
os.remove("example.js")
ast-grep --version
Debug
Known issues
breakingThe exit code behavior of `sg` changed in versions 0.40.2 and 0.40.5. Previously, `sg` would often return 0 even if no matches were found. Now, it correctly returns a non-zero exit code (typically 1) when no matches are found, indicating a 'failure' to find results. This affects scripting where the absence of matches might have been interpreted as success.fixUpdate scripts to explicitly check for `subprocess.run().returncode`. Handle non-zero return codes (e.g., 1) for 'no matches' scenarios if appropriate for your logic. For robust programmatic parsing, always use the `--json` output option, as its structure is more stable than CLI text output regardless of the exit code.
affects: >=0.40.2
gotchaDue to the rapid development of the underlying `ast-grep` tool, CLI arguments, supported languages, and default behaviors can evolve quickly between minor versions. This means scripts or configurations written for one version might behave differently or break with another.fixPin `ast-grep-cli` to a specific minor version (e.g., `ast-grep-cli==0.42.1`) in your production environments and CI/CD pipelines. Review the official GitHub release notes thoroughly when planning an upgrade to a newer minor version. Always consult `sg --help` for the exact options available in your installed version.
affects: All versions
gotchaThe `ast-grep-cli` Python package primarily serves as an installer for the `sg` command-line executable. There is no public, stable Python API designed for programmatic interaction as a traditional library (i.e., by importing classes/functions to manipulate ASTs directly within Python).fixInteract with `ast-grep` in Python scripts by executing the `sg` command using `subprocess.run()` and parsing its standard output. The `--json` output format is highly recommended for machine-readable results.
affects: All versions
breakingThe format and validation rules for `ast-grep` configuration files (e.g., `sgconfig.yml`) can change across versions. For instance, support for `.yaml` extension was fixed in 0.40.0, and unknown keys for patterns were rejected in 0.40.2, indicating stricter parsing.fixEnsure your `sgconfig.yml` files conform to the latest specification by testing with your target `ast-grep-cli` version. Consult the official `ast-grep` documentation and schema for the most current configuration options and syntax. Version control your `sgconfig.yml` files alongside your code.
affects: All versions, especially before 0.40.2
gotchaSupport for specific programming languages and their respective parsers can fluctuate or be refined across `ast-grep` versions. For example, Dart support was re-added in version 0.42.1, indicating that language availability or parser quality can change.fixIf a specific language's support is critical for your use case, thoroughly test your `ast-grep` patterns and rewrites against the desired language in your chosen `ast-grep-cli` version. Consult the `ast-grep` documentation and `sg --list-langs` for the most current list of supported languages and their parser statuses.
affects: All versions
Upgrade
Version history
0.45.2latest on PyPI · released Aug 23, 2026
Audit
Dependencies
No dependency data recorded yet.