【问题标题】:How to call MATLAB library from Python virtual environment on Mac如何在 Mac 上的 Python 虚拟环境中调用 MATLAB 库
【发布时间】:2019-01-18 12:34:36
【问题描述】:

我正在尝试从虚拟环境调用为 macOS 上的 Python 打包的 MATLAB 包。

为了在 macOS 上使用 MATLAB 运行时,DYLD_LIBRARY_PATH must be updated to point to the MATLAB Runtimelibpython3.6.dylib

export DYLD_LIBRARY_PATH="/Applications/MATLAB/MATLAB_Runtime/v95/runtime/maci64:/Applications/MATLAB/MATLAB_Runtime/v95/sys/os/maci64:/Applications/MATLAB/MATLAB_Runtime/v95/bin/maci64:/Library/Frameworks/Python.framework/Versions/3.6/lib:${DYLD_LIBRARY_PATH}"

然后创建并激活 Python 虚拟环境:

$ python3.6 -m venv py36
$ source py36/bin/activate

接下来将MATLAB packaged for Python application 安装到虚拟环境中:

(py36) $ cd /Applications/my_matlab_app/application
(py36) $ python setup.py install
(py36) $ pip list
Package                Version
---------------------- -------
matlabruntimeforpython R2018b 
pip                    18.1   
setuptools             40.6.2 

现在尝试运行一个脚本,在虚拟环境中导入您的 MATLAB 库:

(py36) $ python matlab_test.py 
Exception caught during initialization of Python interface. Details: On the Mac, use 'mwpython' rather than 'python' to start a script or session that will call deployed MATLAB code from Python.
Traceback (most recent call last):
  File "matlab_test.py", line 26, in <module>
    import my_matlab_app
  File "/Users/user/venv/py36/lib/python3.6/site-packages/my_matlab_app/__init__.py", line 283, in <module>
    _pir.import_cppext()
  File "/Users/user/venv/py36/lib/python3.6/site-packages/my_matlab_app/__init__.py", line 276, in import_cppext
    self.cppext_handle = importlib.import_module("matlabruntimeforpython" + self.interpreter_version)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
RuntimeError: On the Mac, use 'mwpython' rather than 'python' to start a script or session that will call deployed MATLAB code from Python.

问题在于,据我所知,mwpython 不能在虚拟环境中使用。有没有办法解决这个问题?我们目前正在努力创建可重复的环境,因为mwpython 似乎硬编码了要全局安装的所有内容。

测试日期:

  • macOS 10.14.2
  • 从 python.org 安装的 Python 3.6.8
  • MATLAB 运行时 2018b

【问题讨论】:

    标签: python python-3.x matlab matlab-deployment python-venv


    【解决方案1】:

    activate 脚本取消设置 PYTHONHOME 并设置 VIRTUAL_ENV,这是您的虚拟环境的文件夹路径。 mwpython 将使用 PYTHONHOME 指向的 python 解释器(当然,假设它是受支持的版本)。因此,您只需要在调用 mwpython 之前设置并导出 PYTHONHOME 到 VIRTUAL_ENV,例如

    python3.6 -m venv py36
    source py36/bin/activate
    
    export PYTHONHOME=$VIRTUAL_ENV
    mwpython matlab_test.py
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 2020-02-10
      • 2017-11-29
      相关资源
      最近更新 更多