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.
Python code
11 linesimport 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
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
- Use `output_filename` instead of 'stdout' to write results directly to a file
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.