ripgrepy Library
ripgrepy is a Python interface to ripgrep, a powerful, line-oriented search tool that recursively searches directories for regex patterns. It functions as a wrapper around the native `ripgrep` binary, allowing users to chain `ripgrep` command-line options directly in Python. The current version is 2.2.0, and the library maintains an active release cadence with updates typically occurring every few months.
Warnings
- breaking Version 2.0.0 changed the internal execution of `run()` to use `subprocess.run` for shell escaping. This might alter how arguments are processed and escaped compared to previous versions, potentially affecting commands with complex or unquoted arguments. It also fixed a bug where numeric arguments were incorrectly cast to strings, which could change behavior if older code relied on that implicit conversion.
- gotcha The `.run()` method must always be the last method called before an output method (e.g., `.as_string()`, `.as_dict()`, `.as_json()`). Any `ripgrep` options chained *after* `.run()` will be ignored and will not be included in the executed command.
- gotcha The `ripgrepy` library is a wrapper around the `ripgrep` command-line tool. It *requires* the `ripgrep` binary to be installed on the system where the Python code is executed. It will not work if the `ripgrep` binary is not found in the system's PATH or explicitly specified during `Ripgrepy` instantiation.
- gotcha Not all output formats from the underlying `ripgrep` binary are compatible with `ripgrepy`'s structured output methods, specifically `.as_dict()` and `.as_json()`. If the `ripgrep` command produces highly verbose or non-standard output, these methods might fail to parse it correctly.
Install
-
pip install ripgrepy
Imports
- Ripgrepy
from ripgrepy import Ripgrepy
Quickstart
import tempfile
import os
from ripgrepy import Ripgrepy
# Create a temporary directory and file for demonstration
with tempfile.TemporaryDirectory() as tmpdir:
test_file_path = os.path.join(tmpdir, 'test_document.txt')
with open(test_file_path, 'w') as f:
f.write('Hello, world!\n')
f.write('This is a test line.\n')
f.write('Another line saying hello.\n')
print(f"Searching in: {tmpdir}")
print(f"Content of {os.path.basename(test_file_path)}:\n---\n{open(test_file_path).read()}---\n")
# Initialize Ripgrepy with a regex pattern and the directory to search
# Note: The 'ripgrep' binary must be installed on your system (e.g., `brew install ripgrep` or `apt install ripgrep`)
rg = Ripgrepy('hello', tmpdir)
# Chain ripgrep options (e.g., --with-filename, --line-number)
# .run() executes the command, followed by an output method
results = rg.with_filename().line_number().run().as_string()
print("Search results (as string):\n---")
print(results)
print("---")
# You can also get results as a dictionary or JSON
# results_dict = rg.run().as_dict()
# print("Search results (as dict):\n---")
# print(results_dict)
# print("---")