我正在尝试在我的新主要Python项目中使用 virtualenv 。代码文件位于〜/ Documents / Project,我在那里安装了一个虚拟环境,位于〜/ Documents / Project / env。我在 env / bin 文件夹中包含了我想要的所有包和库。
问题是,如何使用此虚拟环境实际运行我的Python脚本?我在终端中激活它,然后打开空闲作为测试,然后尝试
“import django”
但它不起作用。基本上,我在运行时如何使用我的项目在虚拟环境中安装库,而不是使用安装的Python库的标准目录?
答案 0 :(得分:2)
查看下面的示例,以及virtualenv文档。如果您按照以下步骤操作,实际上相当简单:
virtualenv Project # creates a new Project dir
cd Project/bin # could just call Project/bin
. activate # should now have (Project) in the prompt name
pip install django # without this, won't be able to import django
deactivate # switch of virtual mode
我在我的Mac上尝试了以上操作并且工作正常。这是一份成绩单供参考。
[MacMini]<Documents> :virtualenv Project
[MacMini]<Project> :cd bin/
[MacMini]<bin> :python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named django
>>> quit()
[MacMini]<bin> :. activate
(Project)[MacMini]<bin> :pip install django
You are using pip version 6.0.6, however version 8.1.0 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting django
Downloading Django-1.9.4-py2.py3-none-any.whl (6.6MB)
100% |################################| 6.6MB 1.2MB/s
Installing collected packages: django
Successfully installed django-1.9.4
(Project)[MacMini]<bin> :python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> quit()
(Project)[MacMini]<bin> :deactivate
答案 1 :(得分:0)
为所有依赖项制作requires.txt文件也是一种很好的做法。例如,如果您的项目需要Flask和pymongo,请创建一个文件:
Flask==<version number you want here>
pymongo==<version number you want here>
然后您可以通过执行以下操作安装所有必需的库:
pip install -r requires.txt
如果您想分享您的项目或者不想记住您在virtualenv中需要的每个库,那就太棒了。