当前位置 : 首页 » 文章分类 :  开发  »  Python-安装与环境配置

Python-安装与环境配置

Python 学习笔记


虚拟环境

Python 中,虚拟环境(Virtual Environment)是一个独立的、隔离的 Python 运行环境,它拥有自己的 Python 解释器、第三方库和应用程序。
通过创建虚拟环境,可以确保项目之间的依赖关系不会相互干扰,每个项目都可以使用自己独立的 Python 解释器和第三方库版本。

Virtualenv 虚拟环境

Virtualenv 是一个用于创建独立 Python 环境的第三方库。
pip install virtualenv 安装 Virtualenv
virtualenv 为应用提供了隔离的 Python 运行环境,解决了不同应用间多版本的冲突问题。


PyCharm

http://www.jetbrains.com/pycharm/

指定源码目录

PyCharm 默认会将项目的根目录标记为源码根目录(Sources Root)
如果项目中源码是在根目录的某个子目录中,比如 src 目录,需要手动将 src 标记为源码根目录:
方法1:Settings -> Project: xxx -> Project Structure -> 选择 src 目录 -> 上面 Mark as: 选择 Sources
方法2:在 src 目录上点右键 -> Mark Directory as -> Sources Root

系统解释器与Virtualenv/Conda虚拟环境

PyCharm 配置中 Settings | Project: xxx | Python Interpreter 可以添加系统全局安装的 Python 解释器(也就是Python版本),也可以添加 Virtualenv/Conda 虚拟环境:

  • 配置已安装的 Python 解释器(已安装的 Python 版本),会造成不同项目环境全局共享,所有项目共用相同依赖,可能导致依赖版本冲突问题。
  • 添加 Virtualenv/Conda 虚拟环境是创建一个独立的虚拟环境,与系统 Python 完全隔离,每个虚拟环境又独立依赖。

创建 Virtualenv 虚拟环境后,再打开 Terminal 看到提示符前有个 (env) 表示处于虚拟环境中。
如果没有 (env),可能由于某种原因未激活虚拟环境,执行下面命令激活虚拟环境:
source venv/bin/activate

.ignore 插件安装及配置

设置 -> Plugins 搜索 .ignore 插件安装。安装后重启 PyCharm
项目上点右键 -> New -> .ignore file -> .gitignore file(Git)
然后配置 .gitignore 文件需要忽略的语言项,选择 Python, JetBrains, VirtualEnv

ImportError: No module named pip

pycharm 中安装依赖包提示 ImportError: No module named pip

这个错误通常发生在尝试使用Python的pip时,PyCharm IDE 无法找到pip模块。这可能是因为pip未正确安装或不在Python的搜索路径中。
解决此问题的方法是确保pip已正确安装,并且可以在PyCharm中访问。
1、检查pip是否已正确安装:在命令行中输入pip --version。如果没有安装pip,请根据需要使用适合您操作系统的pip安装指南进行安装。
2、在PyCharm中配置Python解释器:在设置(Settings)> 项目(Project)> Python解释器(Python Interpreter)中,确保已正确选择Python解释器,并且pip已添加到解释器的“项目解释器”中。

如果本地没有安装 pip,可以直接在 pycharm Settings -> Project -> Python Interpreter -> Add 中选择 Virtualenv Environment,为此项目单独配置一个虚拟环境。


修改默认测试框架

安装 pytest 后,PyCharm 会自动检测到 pytest 并将 pytest 做为默认测试框架。
之后在所有 test_ 开头 或 _test 结尾的文件上点 run 或 debug 时都会走 pytest 测试框架,可能导致 if __name__ == '__main__': 方法无法正常运行。
可以修改 File -> Settings -> Tools -> Python Integrated Tools -> Testing -> Default test runner 设置,能看到 Default test runner 是 Autodetect(pytest),改为一个其他的测试框架比如 Unittests 即可。


Anaconda

Anaconda 是一个包含180+的科学包及其依赖项的发行版本。其包含的科学包包括:conda, numpy, scipy, ipython notebook等

conda 是包及其依赖项和环境的管理工具,适用语言:Python, R, Ruby, Lua, Scala, Java, JavaScript, C/C++, FORTRAN
快速安装、运行和升级包及其依赖项
在计算机中便捷地创建、保存、加载和切换环境

conda 包和环境管理器包含于 Anaconda 的所有版本当中。

Mac 安装 anaconda

brew install anaconda
M1 Mac 安装目录:/opt/homebrew/anaconda3
安装后如果 conda 命令无法使用,编辑 ~/.zshrc 添加 export PATH=$PATH:/opt/homebrew/anaconda3/bin

conda list 查看安装了哪些包

conda env list 查看已创建的环境

或 conda info -e

conda create -n xx python=3.9 创建虚拟环境

创建 python 虚拟环境
conda create -n yourEnv python=x.x
python 版本为x.x,名字为 yourEnv 的虚拟环境。创建完,可以装 anaconda 的目录下找到 envs/yourEnv 目录

例如:

conda create -n py39 python=3.9
## Package Plan ##

  environment location: /opt/homebrew/anaconda3/envs/py39

  added / updated specs:
    - python=3.9


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    openssl-3.0.11             |       h1a28f6b_2         4.2 MB
    pip-23.3                   |   py39hca03da5_0         2.6 MB
    python-3.9.18              |       hb885b13_0        11.6 MB
    setuptools-68.0.0          |   py39hca03da5_0         946 KB
    wheel-0.41.2               |   py39hca03da5_0         107 KB
    ------------------------------------------------------------
                                           Total:        19.5 MB

The following NEW packages will be INSTALLED:

  ca-certificates    pkgs/main/osx-arm64::ca-certificates-2023.08.22-hca03da5_0
  libcxx             pkgs/main/osx-arm64::libcxx-14.0.6-h848a8c0_0
  libffi             pkgs/main/osx-arm64::libffi-3.4.4-hca03da5_0
  ncurses            pkgs/main/osx-arm64::ncurses-6.4-h313beb8_0
  openssl            pkgs/main/osx-arm64::openssl-3.0.11-h1a28f6b_2
  pip                pkgs/main/osx-arm64::pip-23.3-py39hca03da5_0
  python             pkgs/main/osx-arm64::python-3.9.18-hb885b13_0
  readline           pkgs/main/osx-arm64::readline-8.2-h1a28f6b_0
  setuptools         pkgs/main/osx-arm64::setuptools-68.0.0-py39hca03da5_0
  sqlite             pkgs/main/osx-arm64::sqlite-3.41.2-h80987f9_0
  tk                 pkgs/main/osx-arm64::tk-8.6.12-hb8d0fd4_0
  tzdata             pkgs/main/noarch::tzdata-2023c-h04d1e81_0
  wheel              pkgs/main/osx-arm64::wheel-0.41.2-py39hca03da5_0
  xz                 pkgs/main/osx-arm64::xz-5.4.2-h80987f9_0
  zlib               pkgs/main/osx-arm64::zlib-1.2.13-h5a0b063_0

激活虚拟环境

1、linux/mac
source activate yourEnv

source activate py39
(py39)
conda env list
# conda environments:
#
base                     /opt/homebrew/anaconda3
py39                  *  /opt/homebrew/anaconda3/envs/py39

带星号 * 的是当前激活的虚拟环境

2、windows
activate yourEnv

关闭虚拟环境

Linux/Mac 下
conda deactivatesource deactivate py39

删除虚拟环境

conda remove -n your_env_name --all


代替 Anaconda

Anaconda 从 2020 年开始对包括 Miniconda 在内的所有产品商业用途收费。
Miniconda 是 Anaconda 的简化版本,同样受 Anaconda 商业许可条款的约束。
根据 Anaconda 商业许可条款,在营利性组织中使用 Anaconda Individual Edition 超过 200 人时需要购买商业许可,未经授权的商业使用可能带来法律风险。

Miniforge

https://github.com/conda-forge/miniforge

miniforge 集成了 Anaconda 的核心包管理工具 conda,能代替 Anaconda 进行包、环境管理。


Mamba

https://github.com/mamba-org/mamba

mamba 可以兼容所有 conda 命令
mamba 需要依赖 miniforge 这种软件仓库管理包


Linux 安装 Python

Linux 编译安装 Python3.7

很多服务器自带了 python 2

$ python -V
Python 2.7.5
$ whereis python
python: /usr/bin/python /usr/bin/python2.7 /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/include/python2.7 /usr/share/man/man1/python.1.gz
$ ll python*
lrwxrwxrwx. 1 root root    7 1月  29 2019 python -> python2
lrwxrwxrwx. 1 root root    9 1月  29 2019 python2 -> python2.7
-rwxr-xr-x. 1 root root 7216 10月 31 2018 python2.7

安装编译 Python3 需要依赖的包

sudo yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make libffi-devel

安装 pip

#运行这个命令添加epel扩展源
yum -y install epel-release
#安装pip
yum install python-pip

下载 python 3.7
在 python 官网找到下载链接 https://www.python.org/downloadsk/
sudo wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tgz

解压
sudo tar -xzvf Python-3.7.0.tgz

进入 Python-3.7.0 目录,依次执行下面命令进行手动编译
sudo ./configure prefix=/usr/local/python3
如果报错 configure: error: no acceptable C compiler found in $PATH
说明没有安装合适的编译器。这时,需要安装/升级 gcc 及其它依赖包
sudo yum install gcc gcc-c++
安装完后继续执行
sudo ./configure

编译安装
sudo make && make install

1、报错 zipimport.ZipImportError: can’t decompress data; zlib not available
是因为缺少zlib 的相关工具包导致的, 安装zlib相关依赖包
sudo yum install zlib*
只安装 zlib 包后还是会报错,还需一个修改
在重新编译之前还需要在安装源文件中修改 Modules/Setup.dist 文件,将

#zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz

这行前面的注释 # 去掉,保存好再次编译安装

2、报错 /usr/bin/install: 无法删除”/usr/local/bin/python3.7m”: 权限不够
感觉可能是因为我没用root账号执行,su 切换为 root 账号后再编译安装

3、报错 ModuleNotFoundError: No module named ‘_ctypes’
3.7 版本需要一个新的包libffi-devel,安装此包之后再次进行编译安装
yum install libffi-devel
终于安装成。


设置 3.7 为默认版本

安装 3.x 完成后查看版本

$ python3 -V
Python 3.7.4
$ python -V
Python 2.7.16

将原来 python 的软链接重命名(centos 7中默认已有 python2 软链,不需再手动创建)
sudo mv /usr/bin/python /usr/bin/python2
将 python3 链接到 /usr/bin/
sudo ln -s /usr/local/python3/bin/python3.7 /usr/bin/python3.7
将 python3.7 链接到默认python命令 /usr/bin/python, 强制覆盖:
sudo ln -sf /usr/bin/python3.7 /usr/bin/python
这时,再查看 Python 的版本:

$ python -V
Python 3.7.0

输出的是 3.x,说明默认已经使用的是 python3 了

配置 yum 和 yum-utils

升级 Python 之后,由于将默认的 python 指向了 python3,yum 不能正常使用(yum必须用python2),需要编辑 yum 的配置文件:
sudo vim /usr/bin/yum
#!/usr/bin/python 改为 #!/usr/bin/python2,保存退出即可。
如果装了 yum-utils 也需要将 yum-config-manager 脚本中的 python 改为 python2
sudo vim /usr/bin/yum-config-manager
#!/usr/bin/python 改为 #!/usr/bin/python2,保存退出即可。


pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

安装 python3.7 后发现使用 pip 会出现如下报错:

$ pip install flask
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting flask
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
  Could not fetch URL https://pypi.org/simple/flask/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/flask/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
  Could not find a version that satisfies the requirement flask (from versions: )
No matching distribution found for flask
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping

openSSL 是系统自带的,所以一定是安装了的
pip 提示找不到 ssl 模块是因为 在 ./configure 过程中,如果没有加上 –with-ssl 参数时,默认安装的软件涉及到ssl的功能不可用,刚好pip3过程需要ssl模块,而由于没有指定,所以该功能不可用。

cd Python-3.7.4
sudo ./configure --with-ssl
sudo make && install

Linux 离线编译安装 Python 3.13.1

1、下载 Python 3.13.1
https://www.python.org/downloads/release/python-3131/
Gzipped source tarball 版本 https://www.python.org/ftp/python/3.13.1/Python-3.13.1.tgz

2、解压 Python-3.13.1.tgz
进入 Python-3.13.1 目录
执行 ./configure
执行 make
执行 sudo make install
安装到 /usr/local/bin/python3


Mac 安装 Python

Mac 自带 Python 版本

不同 Mac 系统版本自带的 python 版本不同:

  • 早期的 Mac 系统版本自带 Python2
  • 后来有的 Mac 自带了 python2.7 和 python3.x,以及 pip3,但没有 pip2
  • macOS Monterey 升级到 12.3 后不再默认安装 python2,自带 Python3

Python 2.7 was removed from macOS in this update. Developers should use Python 3 or an alternative language instead. (39795874)
macOS Monterey 12.3 Release Notes
https://developer.apple.com/documentation/macos-release-notes/macos-12_3-release-notes

输入 python,默认使用的 python2.7

$ python

WARNING: Python 2.7 is not recommended.
This version is included in macOS for compatibility with legacy software.
Future versions of macOS will not include Python 2.7.
Instead, it is recommended that you transition to using 'python3' from within Terminal.

Python 2.7.18 (default, Nov 13 2021, 06:17:34)

输入 python3,使用 python3.8

python3
Python 3.8.9 (default, Jul 19 2021, 09:37:30)
[Clang 13.0.0 (clang-1300.0.27.3)] on darwin

Mac brew 安装 Python3.9

brew install python3 brew 安装 Python3,默认安装的是 Python3.9

==> Summary
🍺 /opt/homebrew/Cellar/python@3.9/3.9.9: 3,082 files, 56.8MB

Python has been installed as
/opt/homebrew/bin/python3

Unversioned symlinks python, python-config, pip etc. pointing to
python3, python3-config, pip3 etc., respectively, have been installed into
/opt/homebrew/opt/python@3.9/libexec/bin

You can install Python packages with
pip3 install
They will install into the site-package directory
/opt/homebrew/lib/python3.9/site-packages

之后输入 python3.9 可进入 python3.9

python3.9
Python 3.9.9 (main, Nov 21 2021, 03:16:13)
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

Mac 安装 pip(pip2)

Mac 自带 Python2.7 但没有 pip2,有好多老项目中需要用到 pip2,没有的话经常会报错。

cd /Library/Python/2.7
sudo curl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py
python2 get-pip.py

安装后提示

# python get-pip.py
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
Defaulting to user installation because normal site-packages is not writeable
Collecting pip<21.0
  Using cached pip-20.3.4-py2.py3-none-any.whl (1.5 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.3.4
    Uninstalling pip-20.3.4:
      Successfully uninstalled pip-20.3.4
  WARNING: The scripts pip, pip2 and pip2.7 are installed in '/Users/user/Library/Python/2.7/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-20.3.4

加入环境变量:

vim ~/.zshrc
export PATH=${PATH}:/Users/user/Library/Python/2.7/bin
source ~/.zshrc
pip -V
pip 20.3.4 from /Users/user/Library/Python/2.7/lib/python/site-packages/pip (python 2.7)

SIP保护导致包安装报错

PyCharm 安装依赖报错:
ERROR: Could not install packages due to an EnvironmentError: [Errno 1] Operation not permitted: ‘/private/tmp/pip-uninstall-x7akWf/easy_install.py’

原因:
Mac 系统从 OS X El Capitan 开始引入了 SIP(System Integrity Protection) 机制,默认启用 SIP 系统完整性保护机制,限制对系统目录的写操作。
SIP 将一些文件目录和系统应用保护了起来。但这会影响我们一些使用或设置,比如:更改系统应用图标、终端操作系统目录文件提示「Operation not permitted」、Finder 无法编辑系统目录里的文件。
命令行输入 csrutil status 可看到 SIP 是否启用,

csrutil status
System Integrity Protection status: enabled.

解决:
关闭 SIP
重启 Mac 进入恢复模式,M1 Mac 是按住开机键不动,Intel Mac 是启动后按住 Command+R,在恢复模式终端中输入 csrutil disable 禁用 SIP,然后重启即可


Mac 使用 pyenv 管理 Python 版本

pyenv 原理

Mac 上,pyenv 会在 PATH 环境变量的最前面插入一个垫片路径(shims) ~/.pyenv/shims,这个 shims 目录包含了各种 Python 相关命令如python、pip等,但都是指向不同 Python 版本的代理脚本。
当用户执行这些命令时,系统会优先找到 shims 目录中的代理脚本,而不是系统默认的路径(/usr/bin/python)。这样,pyenv 就能够拦截这些命令并根据当前设置的 Python 版本来决定使用哪个版本的解释器。

优先级:

  • 如果当前 Shell 会话通过 pyenv shell 指定了临时版本‌,使用此版本,优先级最高,否则
  • 如果当前目录存在 .python-version 文件(pyenv local 设置)‌,使用此版本,否则
  • 使用 ~/.pyenv/version 中的全局版本号(pyenv global 设置)

Mac brew 安装 pyenv

brew install pyenv 即可安装 pyenv

M1 Mac 安装路径: /opt/homebrew/Cellar/pyenv/2.3.36

执行 pyenv 看到如下输出说明安装成功:

pyenv
pyenv 2.3.36
Usage: pyenv <command> [<args>]

Some useful pyenv commands are:
   --version   Display the version of pyenv
   commands    List all available pyenv commands
   exec        Run an executable with the selected Python version
   global      Set or show the global Python version(s)
   help        Display help for a command
   hooks       List hook scripts for a given pyenv command
   init        Configure the shell environment for pyenv
   install     Install a Python version using python-build
   latest      Print the latest installed or known version with the given prefix
   local       Set or show the local application-specific Python version(s)
   prefix      Display prefixes for Python versions
   rehash      Rehash pyenv shims (run this after installing executables)
   root        Display the root directory where versions and shims are kept
   shell       Set or show the shell-specific Python version
   shims       List existing pyenv shims
   uninstall   Uninstall Python versions
   version     Show the current Python version(s) and its origin
   version-file   Detect the file that sets the current pyenv version
   version-name   Show the current Python version
   version-origin   Explain how the current Python version is set
   versions    List all Python versions available to pyenv
   whence      List all Python versions that contain the given executable
   which       Display the full path to an executable

See `pyenv help <command>' for information on a specific command.
For full documentation, see: https://github.com/pyenv/pyenv#readme

编辑 ~/.zshrc

if command -v pyenv 1>/dev/null 2>&1; then
 eval "$(pyenv init -)"
fi

使用 pyenv 管理 Python 版本

pyenv install -l 查看可安装软件包

pyenv install -l 显示可以安装的软件版本列表,除了 Python 外还有其他相关软件

pyenv install -v 3.9.18 安装指定版本Python

pyenv install 版本号 安装指定版本的 python,必须是 pyenv install -l 列出的 Python 版本号

安装 Python 3.9.18

pyenv install -v 3.9.18
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
/var/folders/5m/qhyq7_1d1f92r9jym_g921t00000gp/T/python-build.20240220145049.98302 ~
Downloading Python-3.9.18.tar.xz...
-> https://www.python.org/ftp/python/3.9.18/Python-3.9.18.tar.xz

由于网络问题,Python 安装包下载很慢,想快速安装可以先手动下载 https://www.python.org/ftp/python/3.9.18/Python-3.9.18.tar.xz
然后进入 ~/.pyenv 目录,创建 cache 子目录,将 Python-3.9.18.tar.xz 拷贝到 cache 目录内

ls cache
Python-3.9.18.tar.xz

再执行 pyenv install -v 3.9.18 便可快速安装:

Successfully installed pip-24.0 setuptools-65.5.0
Installed Python-3.11.8 to /Users/user/.pyenv/versions/3.11.8

pyenv versions 查看已安装的Python环境

pyenv versions 罗列当前已安装的所有 python 环境,如果是当前正在使用的环境,则前面会有个 *
刚安装 pyenv 后,只有 system

pyenv versions
  system
  3.9.18
* 3.11.8 (set by /Users/user/.pyenv/version)

pyenv global 显式全局Python版本

pyenv global 显式当前的全局 Python 版本

pyenv global 3.9.18 设置全局Python版本号

pyenv global 版本号 更改全局 Python 版本,pyenv 会在用户的主目录下生成一个版本文件 ~/.pyenv/version 这个文件记录了全局版本号
注意这里的版本号必须是 pyenv versions 列出的版本号

$ pyenv versions
* system (set by /Users/user/.pyenv/version)
  3.9.18
$ pyenv global 3.9.18

pyenv local 3.9.18 设置当前目录Python版本号

pyenv local 版本号 会在当前目录创建 .python-version 文件,并记录设置的 python 环境,每次进入该目录会自动设置成该 python 环境

pyenv shell 3.9.18 设置当前shell的Python版本号

pyenv shell 版本号 更改当前 shell 下使用的 python 版本,临时生效,优先级高于 global


上一篇 Python-常用模块

下一篇 RIME 鼠须管输入法

阅读
评论
4.8k
阅读预计23分钟
创建日期 2024-12-17
修改日期 2025-03-15
类别
标签

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论