Search code examples
pythontesseractpython-asyncio

How to run a method with blocking behaviour in Python asyncio? Method is from tesseract library for OCR


I have async programm and it is necessary to run a blocking function without blocking event loop. Execution of this function takes aroud 4 seconds. Unfortunately I can`t let it block event loop for such a long time.

Code below says what I want to do.

image = Image.open(image_path)                                   
result = await loop.run_in_executor(None, image_to_string(image ))

However I am getting error:

TypeError: 'str' object is not callable

Could you tell me what is wrong with this code and how can I get desired behaviour?


Solution

  • You almost got it right. The problem is that run_in_executor is a function like any other, so if you pass it image_to_string(image), Python will interpret that as an instruction to call image_to_string immediately, and pass the result of the call to run_in_executor.

    To avoid that interpretation, run_in_executor accepts a function, which it will call on its own, in another thread. The function is optionally followed by arguments, so the correct call looks like this:

    result = await loop.run_in_executor(None, image_to_string, image)