cbr*_*rnr 5 python matplotlib virtualenv pycharm
我在 macOS 10.14.3 上使用通过 Homebrew 安装的 Python 3,并且安装virtualenv了pip:
$ brew install python
$ pip3 install virtualenv
Run Code Online (Sandbox Code Playgroud)
$ virtualenv venv
$ source venv/bin/activate
$ pip install matplotlib ipython
$ ipython
In [1]: %matplotlib
ImportError: Python is not installed as a framework. The Mac OS X backend will
not be able to function correctly if Python is not installed as a framework.
See the Python documentation for more information on installing Python as a
framework on Mac OS X. Please either reinstall Python as a framework, or try
one of the other backends. If you are using (Ana)Conda please install
python.app and replace the use of 'python' with 'pythonw'. See 'Working with
Matplotlib on OSX' in the Matplotlib FAQ for more information.
Run Code Online (Sandbox Code Playgroud)
现在我注意到,如果我使用 PyCharm 创建一个 virtualenv,使用“创建新项目”-“纯 Python”,并将“项目解释器”设置为“使用 Virtualenv 的新环境”,我可以成功地将 Matplotlib 与任何已安装的后端一起使用。假设使用 PyCharm 创建的 virtualenv 位于该文件夹中venv2:
$ source venv2/bin/activate
$ pip install matplotlib ipython
$ ipython
In [1]: %matplotlib
Using matplotlib backend: MacOSX
Run Code Online (Sandbox Code Playgroud)
为什么这有效?PyCharm 如何创建 virtualenv 以便 Matplotlib 工作?他们的文档指出他们也在使用该virtualenv软件包,所以我不知道他们做了什么不同的事情。
请参阅https://matplotlib.org/faq/osx_framework.html
解决方案是不使用 virtualenv,而是使用 stdlib 的 venv,它提供类似的功能,但不会出现此问题。
这是使用virtualenv命令创建的虚拟环境的错误。PyCharm按照上面文档中的建议使用venv命令。
如果您使用venv命令在终端中创建虚拟环境,它应该可以正常工作。