如何在MacOS Mojave上正确安装Python3和Virtualenv?

11
我开始学习Django框架,所以我需要在我的Mac上安装最新的Python、pip、virtualenv和Django包。我尝试使用brew安装,但是遇到一些奇怪的问题。
首先,Python3安装在/Library/Frameworks/Python.framework目录下而不是/usr/bin/。
$ which python
/usr/bin/python
$ which python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3

对我来说很奇怪,因为每个教程都只提到了 /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.

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

Installing collected packages: virtualenv
Successfully installed virtualenv-16.4.3

但是当我尝试创建虚拟环境时,出现了以下错误:
$ virtualenv venv
-bash: /usr/local/bin/virtualenv: No such file or directory

检查 virtualenv 位置:

$ which virtualenv
/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenv

为什么要使用 /Library/Frameworks/Python.framework/?为什么在 /usr/local/bin/virtualenv 中搜索 virtualenv?在 MacOS 上编码总是那么痛苦吗?

https://virtualenvwrapper.readthedocs.io/en/latest/install.html#shell-startup-file 将此添加到您的~/.bashrc文件中,以及这个:VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 - Max
你好,感谢回答。我还有一个问题 - 我是否需要安装virtualenvwrapper?因为我没有virtualenvwrapper.sh脚本... - Trady
此外,我的主文件夹中没有 $HOME/.virtualenvs。 - Trady
已删除所有pip包、pip本身、python,甚至homebrew。重新安装了brew、python3。使用了这个手册:https://docs.python-guide.org/starting/install3/osx/ 现在virtualenv工作正常。所以将尝试安装django并测试它。 - Trady
1
好的,完美!问题可以关闭了。无论如何,感谢您的回答。 - Trady
3个回答

24

你可以使用"venv"而不是使用brew。

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

python3 -m venv environment_name

示例:如果您想为名为django_env的Django创建虚拟环境

python3 -m venv django_env

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

激活虚拟环境:

source django_env/bin/activate

停用:

deactivate

7

Python3虚拟环境设置

要求:

  • Python3
  • Pip3
$ brew install python3 #upgrade

Pip3已经随Python3安装。

安装

使用pip安装virtualenv,请运行以下命令:

$ pip3 install virtualenv

使用方法

创建虚拟环境:

$ virtualenv -p python3 <desired-path>

激活 virtualenv:

$ source <desired-path>/bin/activate

关闭虚拟环境:

$ deactivate

你可以在 官方网站 上了解有关 Homebrew 的更多信息。

抱歉,我无法直接访问外部网站或链接。但是,如果您能提供要翻译的具体文本,我将尽力为您提供中文翻译。 - scottbb
从英文翻译成中文。只返回翻译后的文本:从https://gist.github.com/pandafulmanda/730a9355e088a9970b18275cb9eadef3复制粘贴 - undefined

0

只需按照以下步骤操作:

  1. $ pip install virtualenv 安装完成后,您可以使用以下命令创建虚拟环境:

  2. $ virtualenv [directory] 在 MacOS 上,我们使用 source 命令激活虚拟环境。如果您在 myvenv 目录中创建了 venv,则命令应为

  3. $ source myvenv/bin/activate


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接