2. 在类Unix环境下使用Python¶
2.1. 获得并安装Python的最新版本¶
2.1.1. 在Linux中¶
Python 预装在大多数 Linux 发行版上,并在它们以外的发行版上以软件包的形式提供。 不过在你所用的发行版的软件包中可能没有某些你需要使用的功能。 这时你可以用源代码来编译最新版本的 Python。
对于最新版本的 Python 未预装也不在软件仓库中的情况,你可以为你的发行版制作软件包。 请参阅下面的链接:
参见
- https://www.debian.org/doc/manuals/maint-guide/first.en.html
对于Debian用户
- https://en.opensuse.org/Portal:Packaging
对于OpenSuse用户
- https://docs.fedoraproject.org/en-US/package-maintainers/Packaging_Tutorial_GNU_Hello/
对于Fedora用户
- https://slackbook.org/html/package-management-making-packages.html
对于Slackware用户
2.1.1.1. 安装 IDLE¶
在某些情况下,IDLE 可能未被包括在你的 Python 安装版中。
对于 Debian 和 Ubuntu 用户:
sudo apt update sudo apt install idle
对于 Fedora, RHEL 和 CentOS 用户:
sudo dnf install python3-idle
对于 SUSE 和 OpenSUSE 用户:
sudo zypper install python3-idle
对于 Alpine Linux 用户:
sudo apk add python3-idle
2.1.2. 在FreeBSD和OpenBSD上¶
FreeBSD用户,使用以下命令添加包:
pkg install python3
OpenBSD用户,使用以下命令添加包:
pkg_add -r python pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz
例如:i386用户获取Python 2.5.1的可用版本:
pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz
2.2. 构建Python¶
参见
If you want to contribute to CPython, refer to the devguide, which includes build instructions and other tips on setting up environment.
If you want to compile CPython yourself, first thing you should do is get the source. You can download either the latest release's source or grab a fresh clone. You will also need to install the build requirements.
构建过程由常用命令组成:
./configure
make
make install
特定 Unix 平台的 配置选项 和注意事项通常会详细地记录在 Python 源代码树的根目录下的 README.rst 文件中。
警告
make install 可以覆盖或伪装 python3 二进制文件。因此,建议使用 make altinstall 而不是 make install ,因为后者只安装了 exec_prefix/bin/pythonversion 。
2.4. 杂项¶
要在Unix上使用Python脚本,需要添加可执行权限,例如:
$ chmod +x script
并在脚本的顶部放置一个合适的Shebang线。一个很好的选择通常是:
#!/usr/bin/env python3
将在整个 PATH 中搜索Python解释器。但是,某些Unix系统可能没有 env 命令,因此可能需要将 /usr/bin/python3 硬编码为解释器路径。
要在Python脚本中使用shell命令,请查看 subprocess 模块。
2.5. 自定义 OpenSSL¶
要使用发行商的 OpenSSL 配置和系统信任存储库,请找到包含
openssl.cnf文件或符号链接的目录,它位于/etc中。 在大多数发行版上该文件是在/etc/ssl或者/etc/pki/tls中。 该目录还应当包含一个cert.pem文件和/或一个certs目录。$ find /etc/ -name openssl.cnf -printf "%h\n" /etc/ssl
下载、编译并安装 OpenSSL。 请确保你使用
install_sw而不是install。install_sw的目标不会覆盖openssl.cnf。$ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz $ tar xzf openssl-VERSION $ pushd openssl-VERSION $ ./config \ --prefix=/usr/local/custom-openssl \ --libdir=lib \ --openssldir=/etc/ssl $ make -j1 depend $ make -j8 $ make install_sw $ popd
使用自定义的 OpenSSL 编译 Python (参考配置
--with-openssl和--with-openssl-rpath选项)$ pushd python-3.x.x $ ./configure -C \ --with-openssl=/usr/local/custom-openssl \ --with-openssl-rpath=auto \ --prefix=/usr/local/python-3.x.x $ make -j8 $ make altinstall
备注
OpenSSL 的补丁发布版具有向下兼容的 ABI。 你不需要重新编译 Python 来更新 OpenSSL。 使用一个新的版本来替代自定义 OpenSSL 安装版就可以了。