python - 如何使用 ctypes.util.find_library 在 AWS lambda (python) 中导入 .so 库?
问题描述
我正在尝试什么
我在 Lambda 上使用的 python 包 (OCRMYPDF) 需要 leptonica 库liblept.so.5。在隔离导入代码时,我发现问题出在find_library('lept')上。打印结果返回无。
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(下面的代码)访问该文件。但我不想重写包并将每个 find_library() 替换为 CDLL。是否可以为 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
解决方案
在 Python:3.7 AWS lambda 环境中测试:
您需要将liblept.so
(只需重命名liblept.so.5
)添加到/lib
lambda 包的文件夹或/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
在./lib
LD_LIBRARY_PATH
在 Python 3.8 上,您可能还需要包含ld
and objdump
,根据这个线程:https ://forums.aws.amazon.com/thread.jspa?threadID=313506 ,虽然我没有测试过。
推荐阅读
- vb.net - 这个 RSA 有什么问题,为什么加密/解密的结果不同?
- opengl - EGL 是否需要 GPU?
- bash - 对 package.json 中的 docker 镜像名称进行 Grep
- c# - Polly WaitAndRetry 与最终异常什么都不做
- spring - 如何使用 ThymLeaf 将实体分配给表单中的另一个实体?
- c# - CA1062 未在 .Net Standard 2.0 类库上进行评估
- java - 拒绝名称空间仅在文件扩展名(最后一个点之后的部分)上有所不同的 WSDL 是否合法?
- pyinstaller - 了解 pyinstaller
- c# - 使用 azure-libraries-for-net 在 azure 上的 docker 中执行命令
- mysql - 执行大型查询时 SQL Alchemy 超时