Python 的 C 和 C++ 库如何跨平台?

Max*_*888 8 c c++ python

许多Python 的库,例如Pandas 和Numpy,实际上是C 或C++,并带有Python 包装器。我没有编译语言的经验,也不明白这些库如何跨平台(即在Mac、Windows、Linux上运行),因为我的理解是C和C++需要针对特定​​操作系统进行编译。这是如何运作的?

编辑:
如何为不同操作系统/Python 版本编译 Python C/C++ 扩展?没有回答我的问题,因此这不是重复的。这个问题是关于理解它是如何工作的,这个问题假设了这种理解并且是关于实现的。

App*_*Pie 8

正如评论中指出的,使用 C/C++ 编译代码的 Python 包需要在目标架构上编译才能跨平台。

\n

例如,当您使用时pip install pandas,pip 将在 PyPI 上查找请求的包,如果可用,它将安装wheel与您的特定系统相对应的包。轮子是一种分发机制,有助于在特定的 python 发行版和/或目标架构上安装 python 包。再次以 pandas 为例,这是今天早上 pandas 升级返回的结果:

\n
applepie:~ applepie$ pip install pandas --upgrade\nCollecting pandas\n  Downloading pandas-1.1.3-cp38-cp38-macosx_10_9_x86_64.whl (10.1 MB)\n     |\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88| 10.1 MB 7.2 MB/s \nRequirement already satisfied, skipping upgrade: numpy>=1.15.4 in ./.pyenv/versions/3.8.5/lib/python3.8/site-packages (from pandas) (1.19.2)\nRequirement already satisfied, skipping upgrade: pytz>=2017.2 in ./.pyenv/versions/3.8.5/lib/python3.8/site-packages (from pandas) (2020.1)\nRequirement already satisfied, skipping upgrade: python-dateutil>=2.7.3 in ./.pyenv/versions/3.8.5/lib/python3.8/site-packages (from pandas) (2.8.1)\nRequirement already satisfied, skipping upgrade: six>=1.5 in ./.pyenv/versions/3.8.5/lib/python3.8/site-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)\nInstalling collected packages: pandas\n  Attempting uninstall: pandas\n    Found existing installation: pandas 1.1.2\n    Uninstalling pandas-1.1.2:\n      Successfully uninstalled pandas-1.1.2\nSuccessfully installed pandas-1.1.3\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,执行的第一步是下载与我的特定架构(Mac OSX、x86_64)匹配的 .whl 文件。文件名有更多信息,例如它是 pandas v 1.1.3 并且与 CPython 3.8 兼容。在不同的机器上运行此命令会产生不同的输出。

\n

您可以直接在 PyPI 上查看 pip 可以查找的可用文件列表。同样,在 PyPI 上查找pandas表明,CPython 3.8 上的 Mac OSX 的最新轮子名为 pandas-1.1.3-cp38-cp38-macosx_10_9_x86_64.whl,不出所料,pip install pandas --upgrade\xc2\xa0 下载并安装了它。

\n

我不是 python 分发方面的专家,事实上我最近才接触到 python 轮子,从未分发过 python 代码,并且在回答这个问题之前必须阅读一些内容,但是我的理解是 Python 包含 C/C++ 组件首先需要在每个架构上进行编译,然后为 python 版本和计算机架构的组合构建特定的轮子。如果未找到兼容的轮子,则安装带有 C/C++ 的 Python 包可能需要编译。

\n