关于python中ssl与_ssl循环引用的报错,如何处理?

各位好,最近通过pyinstaller打包文件geopy时,报错如下:

Traceback (most recent call last):
File "entrance.py", line 1, in
File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
File "cover.py", line 16, in
File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
File "geopy_init.py", line 12, in
File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
File "geopy\geocoders_init
.py", line 223, in
File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
File "geopy\geocoders\algolia.py", line 5, in
File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
File "geopy\geocoders\base.py", line 7, in
File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
File "geopy\adapters.py", line 24, in
File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
File "ssl.py", line 99, in
ImportError: DLL load failed while importing _ssl: 找不到指定的模块。

然后我找了下ssl和_ssl这两个文件中的代码。

ssl.py中,有如下语句:

import _ssl             # if we can't import it, let the error propagate

from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
from _ssl import _SSLContext, MemoryBIO, SSLSession
from _ssl import (
    SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
    SSLSyscallError, SSLEOFError, SSLCertVerificationError
    )
from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes

_ssl.py中有如下语句:

# encoding: utf-8
# module _ssl
# from D:\PROGRAM\FORALL\anaconda3\envs\v5\DLLs\_ssl.pyd
# by generator 1.147
"""
Implementation module for SSL socket operations.  See the socket module
for documentation.
"""

# imports
import ssl as __ssl
我的疑惑

比如上图的_ssl.pyd和_ssl.py是什么关系?是因为重名,所以import时出了问题吗?
再就是如下图,中有多个_ssl.py,SIZE区别比较大。但是里面都import了ssl.py是否因为重名出现了问题?

img

而如果将_ssl.py和_ssl.pyd都放入打包路径,就会在刚才报错基础上,增加三行报错如下:

File "D:\PROGRAM\FORALL\anaconda3\envs\v5\DLLs_ssl.py", line 305, in
class SSLCertVerificationError(__ssl.SSLError, ValueError):
AttributeError: partially initialized module 'ssl' has no attribute 'SSLError' (most likely due to a circular import)

######是否有大神遇到过类似问题,或者知道该如何处理,请给予指点。非常感谢!

方案来自 梦想橡皮擦 狂飙组基于 GPT 编写的 “程秘”


这是因为在代码中存在循环导入问题,在一个模块导入了另一个模块,而另一个模块又导入了第一个模块,导致循环导入问题。

解决方法是在循环导入的模块中使用lazy loading,即当真正需要使用该模块时再导入。代码示例:

def foo():
    global bar
    if 'bar' not in globals():
        import bar
    bar.baz()

def baz():
    print("baz")