How to Run Tesseract OCR from Python with subprocess

This script uses Python's subprocess module to invoke the Tesseract OCR engine from the command line and return the extracted text.

Medium Python 3.5+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

11 lines
Python 3.5+
import subprocess

def ocr_image(image_path):
    command = ["tesseract", image_path, "stdout"]
    result = subprocess.run(command, capture_output=True, text=True)
    return result.stdout.strip()

if __name__ == "__main__":
    # Stub: call the actual tesseract (must be installed)
    text = ocr_image("sample.png")
    print(text)

Output

stdout
The extracted text from the image file, e.g., 'Hello World' output to stdout.

How it works

The subprocess.run function spawns the Tesseract executable as a subprocess, passing the image path and 'stdout' as the output destination argument. The capture_output=True parameter captures the standard output stream, and text=True decodes it as a string. The strip() method removes trailing newline characters and whitespace.

Common mistakes

  • Forgetting to install Tesseract or not adding it to PATH
  • Using `shell=True` unnecessarily, which can introduce security risks
  • Not handling errors when Tesseract returns a non-zero exit code

Variations

  1. Use `output_filename` instead of 'stdout' to write results directly to a file
  2. Add `--psm 7` to specify a page segmentation mode for single-line images

Real-world use cases

  • Automating document scanning and digitization pipelines in enterprise workflows.
  • Extracting text from screenshots or images in testing automation frameworks.
  • Processing historical handwritten documents for archival and search indexing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.