在msys2上使用Python

对于 msys2 用户,在 msys2 里使用 Python,Golang 等自然是首选,和 Linux 下体验差不多。本文总结一些 msys2 里使用 Python3 可能会遇到的问题。

版本选择

通过 pacman 搜索,可以看到有两个版本的 Python。

如何选择呢?参考 stackoverflow[1]:

MINGW - Windows native applications

MSYS2 - POSIX applications emulated to work in Windows

MINGW refers to executables that are compiled using the MINGW GCC Compiler and target the Win32 API. MSYS2 refers to executables that are compiled by MSYS2 GCC Compiler and make use of a POSIX emulation layer.

I understand as a user this can be confusing, why do you care which compiler and API Python is compiled against? Well some programs you may want to make use of, are dependent on running in a POSIX environment. It would be very hard and time consuming to port these applications to Windows. In these cases, MSYS2 provides an emulation layer to allow these applications to work. Unfortunately, making use of this emulation layer is very very slow.

So in general, if you can use the MINGW version of Python, you should because it will be much faster. But if you are trying to run a Python application that depends on being in a POSIX environment, then MSYS2 provides an emulation layer to help make it work.

PIP配置文件

使用 pip config edit --editor vim 打开配置文件,一般在 ~/AppData/Roaming/pip/pip.ini

安装包

安装一些需要 gcc 编译的包时,需要安装正确版本的 gcc,根据 Python 版本的选择,安装 msys gcc 或者 mingw64 gcc。否则将会看到如下错误:

即使安装了 gcc,有一部分包仍然不能在 mingw64 下编译,比如 lxml,会报找不到 -lzlib。此时可以考虑使用 msys 版本的 Python。或者直接用 pacman 安装 mingw64 版本的 python-lxml

标准输出乱码

为了兼容性,使用 mintty 时,一般将输出编码设置为 UTF-8,但是 Python 在 msys2 里默认标准输出是 GBK 编码,print 时会是乱码,可以通过设置环境变量解决,在 ~/.bash_profile 中添加

参考资料

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注