Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python asyncio中运行具有阻塞行为的方法?方法来自用于OCR的tesseract库_Python_Tesseract_Python Asyncio - Fatal编程技术网

如何在Python asyncio中运行具有阻塞行为的方法?方法来自用于OCR的tesseract库

如何在Python asyncio中运行具有阻塞行为的方法?方法来自用于OCR的tesseract库,python,tesseract,python-asyncio,Python,Tesseract,Python Asyncio,我有异步程序,有必要在不阻塞事件循环的情况下运行阻塞函数。执行此功能大约需要4秒钟。不幸的是,我不能让它在这么长时间内阻止事件循环 下面的代码说明了我想做什么 image = Image.open(image_path) result = await loop.run_in_executor(None, image_to_string(image )) 然而,我得到了一个错误: TypeError: 'str' object

我有异步程序,有必要在不阻塞事件循环的情况下运行阻塞函数。执行此功能大约需要4秒钟。不幸的是,我不能让它在这么长时间内阻止事件循环

下面的代码说明了我想做什么

image = Image.open(image_path)                                   
result = await loop.run_in_executor(None, image_to_string(image ))
然而,我得到了一个错误:

TypeError: 'str' object is not callable

你能告诉我这个代码有什么问题吗?我怎样才能得到想要的行为?

你几乎做到了。问题是,这是一个与其他函数类似的函数,因此如果将其传递给字符串(image),Python会将其解释为立即调用字符串,并将调用的结果传递给执行器运行

为了避免这种解释,
run_in_executor
在另一个线程中接受一个函数,它将自己调用该函数。函数后面可选地跟有参数,因此正确的调用如下所示:

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