如何使用ctypes.util.find_library导入AWS Lambda(python)中的.so库?

时间:2019-11-28 06:39:16

标签: python aws-lambda ocr ctypes

我在想什么

我在Lambda上使用的(OCRMYPDF)python软件包需要leptonica库 liblept.so.5 。在隔离导入代码时,我发现问题出在 find_library('lept')。打印结果返回None。

from ctypes.util import find_library
def lambda_handler(event, context):
    liblept=find_library('lept')
    print("liblept:%s"%liblept)

我使用的python包需要许多本机编译的依赖项。我正在尝试使用lambda图层导入这些图片。

层结构

/opt/
  /opt/bin/
  /opt/lib/
    /opt/lib/liblept.so.5
  /opt/tesseract

我可以使用CDLL(下面的代码)访问文件。但是我不想重写程序包,并用CDLL替换每个find_library()。可以为find_library设置导入目录吗?

liblept=CDLL("/opt/lib/liblept.so.5") # found
print("liblept:%s"%liblept)

我的图层代码有效

我使用了docker镜像来构建图层。 / opt / bin中依赖于leptonica的文件正在运行(tesseract正常运行,还测试了OCR)。

logging.info(os.system("tesseract --version"))

输出

START RequestId: d826d36c-4ce9-4b67-b501-8c9042edcf80 Version: $LATEST
tesseract 4.1.0
 leptonica-1.78.0
  libgif 5.1.4 : libjpeg 6b (libjpeg-turbo 1.2.90) : libpng 1.2.49 : libtiff 4.0.3 : zlib 1.2.8 : libwebp 0.3.0
 Found AVX
 Found SSE
END RequestId: d826d36c-4ce9-4b67-b501-8c9042edcf80

1 个答案:

答案 0 :(得分:3)

在Python:3.7 AWS lambda环境中测试:

您需要将liblept.so(只需重命名liblept.so.5)添加到lambda包的/lib文件夹中或图层的/opt/lib中。该文件必须称为liblept.so,因为find_library仅查找".so"个文件,而不查找".so.5"个文件:

从python文档中:https://docs.python.org/3/library/ctypes.html

ctypes.util.find_library(name)
Try to find a library and return a pathname. name is the library name without any prefix like lib, suffix like .so, .dylib or version number (this is the form used for the posix linker option -l). If no library can be found, returns None.

仅添加"liblept.so"时,链接器会抱怨找不到"liblept.so.5",所以我也将"liblept.so.5"添加到了lib文件夹中。

也许其他人可以介入并找到不使用重复文件的解决方案。

AWS lambda将自动通过/opt/lib使/libLD_LIBRARY_PATH中的任何文件可用。

在Python 3.8上,根据以下线程:https://forums.aws.amazon.com/thread.jspa?threadID=313506,您可能还需要包括ldobjdump,尽管我还没有测试过。