【问题标题】:Python: ImportError for a module in a script launched from command linePython:从命令行启动的脚本中模块的 ImportError
【发布时间】:2020-09-29 12:22:15
【问题描述】:

有一个由 SWIG 生成的自定义模块“ETPython”(由 ETPython.py 和二进制 _ETPython.so 组成)和一个调用该模块的简单脚本 p>

sample.py

import ETPython
...

如果脚本在 IDE 中运行(pycharm、内部 python 的 IDLE、froglogic 的 squish 等),则不会出现任何问题。但是,如果我尝试在 python shell 中以交互模式或通过终端使用

启动它
python3 sample.py

有如下错误信息:

  File "<path_to_file>/example.py", line 12, in <module>
    import ETPython
  File "<path_to_file>/ETPython.py", line 15, in <module>
    import _ETPython
ImportError: dlopen(<path_to_file>/_ETPython.so, 2): Symbol not found: _NSLog
  Referenced from: <path_to_file>/_ETPython.so
  Expected in: flat namespace

搜索主题,我发现问题与错误的路径有关。所以我添加了一些代码:

import os, sys
os.chdir("<path_to_dir>")
sys.path.append('<path_to_dir>')
os.system('export PYTHONPATH=<path_to_dir>:$PYTHONPATH')

此代码有助于在 python shell 中以交互模式导入模块,但在终端中启动仍然失败。

那么问题是如何让它发挥作用?

【问题讨论】:

  • 代替sys.path.append('&lt;path_to_dir&gt;'),试试sys.path.insert(0, '&lt;path_to_dir&gt;')
  • 如果您有自定义路径,请查看sitecustomize.py
  • @inspectorG4dget,它没有帮助

标签: python macos terminal swig


【解决方案1】:

我找到了解决方案。 SWIG 模块编译不正确。 CMake 有一个选项可以抑制未定义符号的错误

set(PLATFORM_LIBS "-undefined dynamic_lookup" )

这就是为什么模块不包含 NSLOG 符号的原因。 该模块被重新编译了额外的

"-framework Foundation"

在 swig_link_libraries 语句中。现在模块已正确导入

【讨论】:

    猜你喜欢
    • 2013-09-17
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2011-10-30
    • 1970-01-01
    • 2018-09-06
    • 2015-02-06
    相关资源
    最近更新 更多