Python Ripgrep

0.0.9 · active · verified Thu Apr 16

python-ripgrep is a Python wrapper for the high-performance ripgrep command-line utility. It provides a programmatic interface to run ripgrep searches, parse results, and interact with its various options. Currently at version 0.0.9, its release cadence is irregular, with updates typically occurring to add new features or align with upstream ripgrep changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Ripgrep wrapper and perform a basic case-insensitive search for a term in text files. It includes setup for a dummy file and error handling for the missing `ripgrep` executable.

import os
from python_ripgrep import Ripgrep

# Ensure ripgrep is installed and in your PATH.
# For example:
# Debian/Ubuntu: sudo apt install ripgrep
# macOS (Homebrew): brew install ripgrep
# Rust cargo: cargo install ripgrep

# Create a dummy file for searching if it doesn't exist
if not os.path.exists("example_rg.txt"):
    with open("example_rg.txt", "w") as f:
        f.write("Hello, World!\n")
        f.write("This is a test line.\n")
        f.write("Another line with 'World'.\n")
        f.write("hello world again.\n")

try:
    # Initialize Ripgrep instance, searching in the current directory
    # You can also specify a different path: rg = Ripgrep(path='/path/to/project')
    rg = Ripgrep(path='.')

    # Perform a case-insensitive search for "world" in .txt files
    # The search method returns an iterator over results
    print("Searching for 'world' (case-insensitive) in .txt files:")
    results = rg.search('world', file_type='.txt', ignorecase=True)

    found_results = False
    for result in results:
        found_results = True
        print(f"File: {result.file}, Line: {result.line_number}, Match: '{result.match}'")

    if not found_results:
        print("No results found.")

except FileNotFoundError as e:
    if "No such file or directory: 'rg'" in str(e):
        print("\nERROR: ripgrep executable 'rg' not found in your PATH.")
        print("Please install ripgrep from: https://github.com/BurntSushi/ripgrep#installation")
    else:
        print(f"\nAn unexpected FileNotFoundError occurred: {e}")
except Exception as e:
    print(f"\nAn error occurred: {e}")

finally:
    # Clean up the dummy file
    if os.path.exists("example_rg.txt"):
        os.remove("example_rg.txt")

view raw JSON →