如何在 MacOS Mojave 上正确安装 python3 和 virtualenv?

Tra*_*ady 12 python macos homebrew virtualenv python-3.x

我开始学习 Django 框架,所以我需要在我的 mac 上安装最新的 python、pip、virtualenv 和 django 包。我尝试用brew来做到这一点,但我得到了一些奇怪的行为。

首先,python3没有安装在/usr/bin/中,而是安装在/Library/Frameworks/Python.framework目录中:

$ which python
/usr/bin/python
$ which python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
Run Code Online (Sandbox Code Playgroud)

这对我来说很奇怪,因为每个教程都讲述了 /usr/bin/python37 而没有讲述 /Library/Frameworks/Python.framework 这样可以吗?

之后我做出sudo pip3 install virtualenv并得到了这个答案:

The directory '/Users/user/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/user/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Run Code Online (Sandbox Code Playgroud)

好的,我使用 -H sudo 标志进行卸载和安装:

Installing collected packages: virtualenv
Successfully installed virtualenv-16.4.3
Run Code Online (Sandbox Code Playgroud)

但是当我尝试创建虚拟环境时,我得到了

$ virtualenv venv
-bash: /usr/local/bin/virtualenv: No such file or directory
Run Code Online (Sandbox Code Playgroud)

检查 virtualenv 位置:

$ which virtualenv
/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenv
Run Code Online (Sandbox Code Playgroud)

为什么是/Library/Frameworks/Python.framework/?为什么它在 /usr/local/bin/virtualenv 中搜索 virtualenv?在Macos上写代码总是那么痛苦?

小智 25

您可以简单地使用“venv”,而不是使用brew。

要创建虚拟环境,您可以运行 -->

python3 -m venv environment_name
Run Code Online (Sandbox Code Playgroud)

示例:如果要为 django 创建一个名为 django_env 的虚拟环境

python3 -m venv django_env
Run Code Online (Sandbox Code Playgroud)

“-m”标志检查 sys.path 并执行主模块。

激活虚拟环境:

source django_env/bin/activate
Run Code Online (Sandbox Code Playgroud)

停用:

deactivate
Run Code Online (Sandbox Code Playgroud)


Mil*_*vić 7

Python3 虚拟环境设置

要求:

  • Python3
  • 点3
$ brew install python3 #upgrade
Run Code Online (Sandbox Code Playgroud)

Pip3随Python3一起安装

安装

要通过 pip 运行安装 virtualenv:

$ pip3 install virtualenv
Run Code Online (Sandbox Code Playgroud)

用法

创建虚拟环境:

$ virtualenv -p python3 <desired-path>
Run Code Online (Sandbox Code Playgroud)

激活虚拟环境:

$ source <desired-path>/bin/activate
Run Code Online (Sandbox Code Playgroud)

停用虚拟环境:

$ deactivate
Run Code Online (Sandbox Code Playgroud)

您可以在官方页面Homebrew上查看更多相关信息。