Julia:无法将PyCall配置为使用其他版本 注意

问题描述

我想在我的Julia代码中使用一系列Python库。我一直在尝试使用PyCall来访问已经安装在Windows PC上的Python库。但是,我无法从其认的Python发行版(不属于Julia的认Python发行版)重新配置PyCall。按照文档(https://github.com/JuliaPy/PyCall.jl)中的步骤,我在Julia中尝试了以下操作:

using Pkg

ENV["PYTHON"] = raw"C:\Users\catod\AppData\Local\Programs\Python\python37-32\python.exe"

Pkg.build(PyCall)

退出并重新进入Julia后,我尝试跑步

using PyCall

plt = pyimport("matplotlib.pyplot")

但收到以下错误消息:

ERROR: LoadError: PyError (PyImport_ImportModule

The Python package matplotlib.pyplot Could not be imported by pyimport. Usually this means
that you did not install matplotlib.pyplot in the Python version being used by PyCall.    

PyCall is currently configured to use the Julia-specific Python distribution
installed by the Conda.jl package.  To install the matplotlib.pyplot module,you can      
use `pyimport_conda("matplotlib.pyplot",PKG)`,where PKG is the Anaconda
package the contains the module matplotlib.pyplot,or alternatively you can use the
Conda package directly (via `using Conda` followed by `Conda.add` etcetera).

Alternatively,if you want to use a different Python distribution on your
system,such as a system-wide Python (as opposed to the Julia-specific Python),you can re-configure PyCall with that Python.   As explained in the PyCall
documentation,set ENV["PYTHON"] to the path/name of the python executable
you want to use,run Pkg.build("PyCall"),and re-launch Julia.

) <class 'ModuleNotFoundError'>
ModuleNotFoundError("No module named 'matplotlib'")

任何人都可以指出我出了错吗?

解决方法

这里有两个问题:

  1. Matplotlib未安装在您的Python安装中。您需要运行(但是我绝对推荐使用Anaconda,请参阅末尾的注释)

    pip install matplotlib
    
  2. 即使您设法安装matplolib,您的代码也会非常丑陋,因为您无法直接将show嵌入到Julia中,因此您尝试matlplotlib的第一个情节会崩溃而不加载PyPlot。因此,您的代码应为:

    using PyCall
    using PyPlot
    plt = pyimport("matplotlib.pyplot")
    

现在另一个问题是通常PyPlot正在通过conda安装它需要的所有软件包。由于您尝试使用普通的Python,因此需要手动安装这些软件包。

注意

基本上,应该使用Anaconda来获得良好的Julia-Python体验,因为在这种情况下,有许多工具可以使集成自动化。

使用Julia内置的Python是最简单的选择。我绝对推荐:

ENV["PYTHON"] = ""
pkg"build PyCall"
using Conda
Conda.add("matplotlib")

另一个相对容易的选择是Anaconda。安装您自己的Anaconda并将其设置为ENV["PYTHON"]build即可使用。 使用非Anaconda Python永远不会很好,因为您仍然无法使用Conda.jl来管理安装。