ripgrepy Library

2.2.0 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `Ripgrepy` with a search pattern and a target directory (a temporary one in this example). It shows how to chain `ripgrep`'s command-line options like `with_filename()` and `line_number()`, execute the search with `run()`, and retrieve the output as a string. It also highlights the requirement for the underlying `ripgrep` binary to be installed on the system.

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("---")

view raw JSON →