Python 如何在 PyCharm 的终端中激活 virtualenv?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22288569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I activate a virtualenv inside PyCharm's terminal?
提问by Chris Cogdon
I've set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine.
我已经设置了 PyCharm,创建了我的 virtualenv(通过 virtual env 命令,或直接在 PyCharm 中)并激活该环境作为我的解释器。一切正常。
However, if I open a terminal using "Tools, Open Terminal", the shell prompt supplied is notusing the virtual env; I still have to use source ~/envs/someenv/bin/activatewithin that Terminal to activate it.
但是,如果我使用“工具,打开终端”打开终端,则提供的 shell 提示未使用虚拟环境;我仍然必须source ~/envs/someenv/bin/activate在该终端内使用才能激活它。
Another method is to activate the environment in a shell, and run PyCharm from that environment. This is "workable" but pretty ugly, and means I have major problems if I switch environments or projects from PyCharm: I'm now using the totally-wrong environment.
另一种方法是在 shell 中激活环境,然后从该环境运行 PyCharm。这是“可行的”但非常丑陋,这意味着如果我从 PyCharm 切换环境或项目,我会遇到重大问题:我现在使用的是完全错误的环境。
Is there some other, much-easier way to have "Tools, Open Terminal" automatically activate the virtual environment?
还有其他更简单的方法可以让“工具,打开终端”自动激活虚拟环境吗?
采纳答案by Peter Gibson
Edit:
编辑:
According to https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal, PyCharm 2016.3 (released Nov 2016) has virutalenv support for terminals out of the box
根据https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal,PyCharm 2016.3(2016 年 11 月发布)对开箱即用的终端提供了 virutalenv 支持
Auto virtualenv is supported for bash, zsh, fish, and Windows cmd. You can customize your shell preference in Settings (Preferences) | Tools | Terminal.
bash、zsh、fish 和 Windows cmd 支持自动 virtualenv。您可以在设置(首选项)| 中自定义您的外壳首选项。工具 | 终端。
Old Method:旧方法:
Create a file .pycharmrcin your home folder with the following contents
.pycharmrc在您的主文件夹中创建一个包含以下内容的文件
source ~/.bashrc
source ~/pycharmvenv/bin/activate
Using your virtualenv path as the last parameter.
使用您的 virtualenv 路径作为最后一个参数。
Then set the shell Preferences->Project Settings->Shell path to
然后将shell Preferences->Project Settings->Shell path 设置为
/bin/bash --rcfile ~/.pycharmrc
回答by Chris Cogdon
Based on answers from Peter and experimentation, I've come up with a good "general solution", which solves the following:
根据彼得的回答和实验,我想出了一个很好的“通用解决方案”,它解决了以下问题:
- Restores the behaviour of a login shell. PyCharm normally runs a login shell, but --rcfile stopped this happening. Script still uses --rcfile, but attempts to emulate the INVOCATION behaviour of a login shell.
- Removes the need to create an rcfile for each environment
- Removes the need to update the project settings if you change the environment.
- 恢复登录 shell 的行为。PyCharm 通常运行登录 shell,但 --rcfile 阻止了这种情况的发生。脚本仍然使用--rcfile,但尝试模拟登录shell 的INVOCATION 行为。
- 无需为每个环境创建 rcfile
- 如果您更改环境,则无需更新项目设置。
Drop this script into a bin directory somewhere. E.g. ~/bin/pycharmactivate
将此脚本放入某个 bin 目录中。例如 ~/bin/pycharmactivate
if [ -r "/etc/profile" ] ; then . /etc/profile ; fi
if [ -r "~/.bash_profile" ] ; then
. ~/.bash_profile
elif [ -r "~/.bash_login" ] ; then
. ~/.bash_login
elif [ -r "~/.profile" ] ; then
. ~/.profile
fi
ACTIVATERC=`cat .idea/workspace.xml | perl -n -e 'print "$1/bin/activate" if m:option name="SDK_HOME" value="\$USER_HOME\$(.*)/bin/python":'`
if [ -n "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; else echo "Could not find virtualenv from PyCharm" ; fi
Then set PyCharm's Shell path to:
然后将 PyCharm 的 Shell 路径设置为:
/bin/bash --rcfile ~/bin/pycharmactivate
回答by SaeX
Update:
更新:
The preferences in Settings (Preferences) | Tools | Terminal are global.
If you use a venv for each project, remember to use current path variable and a default venv name:
设置(Preferences)中的首选项| 工具 | 终端是全球性的。
如果您为每个项目使用 venv,请记住使用当前路径变量和默认 venv 名称:
"cmd.exe" /k ""%CD%\venv\Scripts\activate""
For Windows users: when using PyCharm with a virtual environment, you can use the /Kparameter to cmd.exeto set the virtual environment automatically.
对于 Windows 用户:在虚拟环境中使用 PyCharm 时,可以使用/K参数 tocmd.exe自动设置虚拟环境。
PyCharm 3 or 4: Settings, Terminal, Default shelland add /K <path-to-your-activate.bat>.
PyCharm 3 或 4: Settings, Terminal,Default shell并添加/K <path-to-your-activate.bat>.
PyCharm 5: Settings, Tools, Terminal, and add /K <path-to-your-activate.bat>to Shell path.
PyCharm 5: ,Settings,Tools,Terminal并添加/K <path-to-your-activate.bat>到Shell path。
PyCharm 2016.1 or 2016.2: Settings, Tools, Terminal, and add ""/K <path-to-your-activate.bat>""to Shell pathand add (mind the quotes). Also add quotes around cmd.exe, resulting in:
PyCharm 2016.1 或 2016.2: Settings, Tools, Terminal, and add ""/K <path-to-your-activate.bat>""to Shell pathand add(注意引号)。还要在 cmd.exe 周围添加引号,导致:
"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""
"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""
回答by SaeX
For Windows users when using PyCharm and a virtual environment under Windows, you can use the /k parameter to cmd.exe to set the virtual environment automatically.
Windows 用户在使用 PyCharm 和 Windows 下的虚拟环境时,可以使用 cmd.exe 的 /k 参数自动设置虚拟环境。
Go to Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>.
转到设置、终端、默认 shell 并添加/K <path-to-your-activate.bat>.
I don't have the reputation to comment on the earlier response so posting this corrected version. This really saves a LOT of time.
我没有资格评论之前的回复,所以发布这个更正的版本。这确实节省了很多时间。
Update:
更新:
Note: Pycharm now supports virtual environments directly and it seems to work well for me - so my workaround not needed anymore.
注意:Pycharm 现在直接支持虚拟环境,它似乎对我来说效果很好——所以我的解决方法不再需要了。
回答by SaeX
Thanks Chris, your script worked for some projects but not all on my machine. Here is a script that I wrote and I hope anyone finds it useful.
谢谢克里斯,您的脚本适用于某些项目,但不适用于我的机器。这是我写的一个脚本,我希望任何人都觉得它有用。
#Stored in ~/.pycharmrc
ACTIVATERC=$(python -c 'import re
import os
from glob import glob
try:
#sets Current Working Directory to _the_projects .idea folder
os.chdir(os.getcwd()+"/.idea")
#gets every file in the cwd and sets _the_projects iml file
for file in glob("*"):
if re.match("(.*).iml", file):
project_iml_file = file
#gets _the_virtual_env for _the_project
for line in open(project_iml_file):
env_name = re.findall("~/(.*)\" jdkType", line.strip())
# created or changed a virtual_env after project creation? this will be true
if env_name:
print env_name[0] + "/bin/activate"
break
inherited = re.findall("type=\"inheritedJdk\"", line.strip())
# set a virtual_env during project creation? this will be true
if inherited:
break
# find _the_virtual_env in misc.xml
if inherited:
for line in open("misc.xml").readlines():
env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
if env_at_project_creation:
print env_at_project_creation[0] + "/bin/activate"
break
finally:
pass
')
if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi
回答by user2684827
I have a solution that worked on my Windows 7 machine.
我有一个适用于我的 Windows 7 机器的解决方案。
I believe PyCharm's terminal is a result of it running cmd.exe, which will load the Windows PATHvariable, and use the version of Python that it finds first within that PATH. To edit this variable, right click My Computer--> Properties--> Advanced System Settings--> Advancedtab --> Environment Variables...button. Within the System variablessection, select and edit the PATHvariable.
我相信 PyCharm 的终端是它运行的结果,它将cmd.exe加载 WindowsPATH变量,并使用它首先在该PATH. 要编辑此变量,请右键单击我的电脑-->属性-->高级系统设置-->高级选项卡 -->环境变量...按钮。在系统变量部分中,选择并编辑PATH变量。
Here is the relevant part of my PATHbeforeediting:
这是我编辑PATH前的相关部分:
C:\Python27\;
C:\Python27\Lib\site-packages\pip\;
C:\Python27\Scripts;
C:\Python27\Lib\site-packages\django\bin;
C:\Python27\;
C:\Python27\Lib\site-packages\pip\;
C:\Python27\Scripts;
C:\Python27\Lib\site-packages\django\bin;
...and afterediting PATH(only 3 lines now):
...编辑后PATH(现在只有 3 行):
C:[project_path]\virtualenv-Py2.7_Dj1.7\Lib\site-packages\pip;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Scripts;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Lib\site-packages\django\bin;
C:[project_path]\virtualenv-Py2.7_Dj1.7\Lib\site-packages\pip;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Scripts;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Lib\site-packages\django\bin;
To test this, open a newwindows terminal (Start--> type in cmdand hit Enter) and see if it's using your virtual environment. If that works, restart PyCharmand then test it out in PyCharm's terminal.
要对此进行测试,请打开一个新的Windows 终端(开始--> 输入cmd并点击Enter)并查看它是否正在使用您的虚拟环境。如果可行,请重新启动 PyCharm,然后在 PyCharm 的终端中对其进行测试。
回答by user4304103
I just added a script named pycharmactivate to my home directory. Set value of PyCharm (4.0.1) File > Settings > Tools > Terminal > Shell path to /bin/bash --rcfile ~/pycharmactivate. Maybe not the best solution incase you have different project and virtualenv directories/names but it works for me. This script contains the following 3 lines and assumes your virtualenv has the same name as your project dir.
我刚刚在我的主目录中添加了一个名为 pycharmactivate 的脚本。将 PyCharm (4.0.1) File > Settings > Tools > Terminal > Shell path 的值设置为 /bin/bash --rcfile ~/pycharmactivate。也许不是最好的解决方案,因为您有不同的项目和 virtualenv 目录/名称,但它对我有用。此脚本包含以下 3 行,并假设您的 virtualenv 与您的项目目录具有相同的名称。
source ~/.bashrc
projectdir=${PWD##*/}
source ~/.virtualenvs/$projectdir/bin/activate
回答by ksaylor11
Another alternative is to use virtualenvwrapperto manage your virtual environments. It appears that once the virtualenvwrapper script is activated, pycharm can use that and then the simple workoncommand will be available from the pycharm console and present you with the available virtual environments:
另一种选择是使用virtualenvwrapper来管理您的虚拟环境。似乎一旦 virtualenvwrapper脚本被激活,pycharm 就可以使用它,然后workon可以从 pycharm 控制台使用简单的命令,并为您提供可用的虚拟环境:
kevin@debian:~/Development/django-tutorial$ workon
django-tutorial
FlaskHF
SQLAlchemy
themarkdownapp
kevin@debian:~/Development/django-tutorial$ workon django-tutorial
(django-tutorial)kevin@debian:~/Development/django-tutorial$
回答by pferate
PyCharm 4 now has virtualenvs integrated in the IDE. When selecting your project interpreter, you can create, add, or select a virtualenv. They've added a "Python Console" that runs in the configured project interpreter.
PyCharm 4 现在在 IDE 中集成了 virtualenvs。选择项目解释器时,您可以创建、添加或选择一个 virtualenv。他们添加了一个在配置的项目解释器中运行的“Python 控制台”。
回答by phiree
this is what i am doing: create a activate_env.bat(windows,maybe .sh in linux) file in the source code folde:
这就是我正在做的:在源代码文件夹中创建一个 activate_env.bat(windows,maybe .sh in linux) 文件:
/env_yourenvlocate/scripts/activate.bat
and another file deactivate_env.bat:
和另一个文件deactivate_env.bat:
/env_yourenvlocate/scripts/deactivate.bat
everytime open the terminal window, just execute the bat file to activate/deactivate the virtualenv, you will stay in source code path, no need to change path to and back.
每次打开终端窗口,只需执行bat文件来激活/停用virtualenv,您将停留在源代码路径中,无需更改路径来回。
E:\Projects\django_study\src>active_env.bat
E:\Projects\django_study\src>../env_django_study/scripts/activate.bat
(env_django_study) E:\Projects\django_study\src>
(env_django_study) E:\Projects\django_study\src>deactive_env.bat
(env_django_study)E:\Projects\django_study\src>../env_django_study/scripts/deactivate.bat
E:\Projects\django_study\src>

