[python] How do I activate a virtualenv inside PyCharm's terminal?

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.

However, if I open a terminal using "Tools, Open Terminal", the shell prompt supplied is not using the virtual env; I still have to use source ~/envs/someenv/bin/activate within that Terminal to activate it.

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.

Is there some other, much-easier way to have "Tools, Open Terminal" automatically activate the virtual environment?

This question is related to python django shell virtualenv pycharm

The answer is


I wanted a separate virtual environment for each project, and didn't care much for having additional files to facilitate this. A solution which you only need to do once and works for all projects is then adding the following to your .bashrc or .bash_profile:

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

This checks if there is a virtual environment where the terminal is being opened, and if so activates it (and of course other relative paths could be used). PyCharm's terminal settings can be left as their default.


One option you have when you enter the terminal > Run > Debug > Edit Configurations enter image description here

enter image description here

select the appropriate conda environmnent.. Also when you create a new project - it asks to configure this location.


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:

"cmd.exe" /k ""%CD%\venv\Scripts\activate"" 

For Windows users: when using PyCharm with a virtual environment, you can use the /K parameter to cmd.exe to set the virtual environment automatically.

PyCharm 3 or 4: Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>.

PyCharm 5: Settings, Tools, Terminal, and add /K <path-to-your-activate.bat> to Shell path.

PyCharm 2016.1 or 2016.2: Settings, Tools, Terminal, and add ""/K <path-to-your-activate.bat>"" to Shell path and add (mind the quotes). Also add quotes around cmd.exe, resulting in:

"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""


Following up on Peter's answer, here the Mac version of the .pycharmrc file:

source /etc/profile
source ~/.bash_profile
source  <venv_dir>/bin/activate

Hen



PyCharm 4.5.4

Create a file .pycharmrc in your home folder with the following contents

source ~/.bashrc
source ~/pycharmvenv/bin/activate

Using your virtualenv path as the last parameter.

Then set the shell Preferences->Project Settings->Shell path to

/bin/bash --rcfile ~/.pycharmrc

I don't why, but it doesn't work for me. PyCharm prints an error.

cmd.exe /K "<path-to-your-activate.bat>" It works, but it creates the same virtualenv for each project, and even if this is not necessary.

This receipt is working! But the string /env_yourenvlocate/scripts/activate.bat must contain quotes, like this "Full_path_to_your_env_locate\scripts\activate.bat"!

Deactivate the virtualenv is very easy - type in the terminal 'deactivate'

(virt_env) D:\Projects\src>deactivate
D:\Projects\src>

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.

Drop this script into a bin directory somewhere. E.g. ~/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:

/bin/bash --rcfile ~/bin/pycharmactivate

This method should work with arbitrary virtual environments per project and it doesn't make assumptions on your environment as it is using hooks you create.

You write:

  • A global script that invokes the hook
  • A hook script per PyCharm project (not mandatory)

Given that the current latest PyCharm (Community 2016.1) does not allow for Terminal settings per project start with the script that invokes the project specific hook. This is my ~/.pycharmrc:

if [ -r ".pycharm/term-activate" ]; then
   echo "Terminal activation hook detected."
   echo "Loading Bash profile..."
   source ~/.bash_profile
   echo "Activating terminal hook..."
   source ".pycharm/term-activate"
   source activate $PYCHARM_VENV
fi

If you are using something other than Bash, invoke your own .bash_profile equivalent should you wish to.

Now set your PyCharm "Tools -> Terminal -> Shell Path" to invoke this script, e.g.: /bin/bash --rcfile ~/.pycharmrc

Finally, for every PyCharm project you need a specific virtual environment activated, create a file within the PyCharm project root .pycharm/term-activate. This is your hook and it will simply define the name of the desired virtual environment for your PyCharm project:

export PYCHARM_VENV=<your-virtual-env-name>

You can of course extend your hooks with anything you find useful in the terminal environment of your particular PyCharm project.


Solution for WSL (Ubuntu on Windows)

If you're using WSL (Ubuntu on Windows), you can also open bash as terminal in pycharm and activate a linux virtualenv.

Use a .pycharmrc file like described in Peter Gibson's answer; Add the .pycharmrc file to your home directory with following content:

source ~/.bashrc
source ~/path_to_virtualenv/bin/activate

In Pycharm File > Settings > Tools > Terminal add the following 'Shell path':

"C:/Windows/system32/bash.exe" -c "bash --rcfile ~/.pycharmrc"


Project specific virtualenv

The path to your virtualenv in .pycharmrc does not have to be absolute. You can set a project specific virtualenv by setting a relative path from your project directory. My virtualenv is always located in a 'venv' folder under my project directory, so my .pycharmrc file looks like this:

source ~/.bashrc
source ~/pycharmvenv/bin/activate #absolute path
source ./venv/bin/activate #relative path


BONUS: automatically open ssh tunnel to connect virtualenv as project interpreter

Add the following to your .pycharmrc file:

if [ $(ps -aux | grep -c 'ssh') -lt 2 ]; then
    sudo service ssh start 
fi

This checks if a ssh tunnel is already opened, and opens one otherwise. In File -> Settings -> Project -> Project Interpreter in Pycharm, add a new remote interpreter with following configuration:

+--------------------------+---------------------------------+-------+----+
| Name:                    | <Interpreter name>              |       |    |
| Select                   | 'SSH Credentials'               |       |    |
| Host:                    | 127.0.0.1                       | Port: | 22 |
| User:                    | <Linux username>                |       |    |
| Auth type:               | 'Password'                      |       |    |
| Password:                | <Linux password>                |       |    |
| Python interpreter path: | <Linux path to your virtualenv> |       |    |
| Python helpers path:     | <Set automatically>             |       |    |
+--------------------------+---------------------------------+-------+----+

Now when you open your project, your bash automatically starts in your virtualenv, opens a ssh tunnel, and pycharm connects the virtualenv as remote interpreter.

warning: the last update in Windows automatically starts a SshBroker and SshProxy service on startup. These block the ssh tunnel from linux to windows. You can stop these services in Task Manager -> Services, after which everything will work again.


If your Pycharm 2016.1.4v and higher you should use "default path" /K "<path-to-your-activate.bat>" don't forget quotes


I have a solution that worked on my Windows 7 machine.

I believe PyCharm's terminal is a result of it running cmd.exe, which will load the Windows PATH variable, 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 --> Advanced tab --> Environment Variables... button. Within the System variables section, select and edit the PATH variable.

Here is the relevant part of my PATH before editing:

C:\Python27\;
C:\Python27\Lib\site-packages\pip\;
C:\Python27\Scripts;
C:\Python27\Lib\site-packages\django\bin;

...and after editing PATH (only 3 lines now):

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 new windows terminal (Start --> type in cmd and hit Enter) and see if it's using your virtual environment. If that works, restart PyCharm and then test it out in PyCharm's terminal.


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.

Go to Settings, Terminal, Default shell and add /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.


Another alternative is to use virtualenvwrapper to manage your virtual environments. It appears that once the virtualenvwrapper script is activated, pycharm can use that and then the simple workon command will be available from the pycharm console and present you with the available virtual environments:

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$ 

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

If you have moved your project to another directory, you can set the new path via Settings dialog. And then you need to set this Project Interpreter in the Edit Configuration dialog.

enter image description here

enter image description here


If You are using windows version it is quite easy. If you already have the virtual environment just navigate to its folder, find activate.bat inside Scripts folder. copy it's full path and paste it in pycharm's terminal then press Enter and you're done!

If you need to create new virtual environment :

Go to files > settings then search for project interpreter, open it, click on gear button and create the environment wherever you want and then follow first paragraph.

The Gear!


I had the same problem with venv in PyCharm. But It is not big problem! Just do:

  1. enter in your terminal venv directory( cd venv/Scripts/ )
  2. You will see activate.bat
  3. Just enter activate.bat in your terminal after this you will see YOUR ( venv )

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.

source ~/.bashrc
projectdir=${PWD##*/}
source ~/.virtualenvs/$projectdir/bin/activate

this is what i am doing: create a activate_env.bat(windows,maybe .sh in linux) file in the source code folde:

/env_yourenvlocate/scripts/activate.bat

and another file 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.

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>

I have viewed all of the answers above but none of them is elegant enough for me. In Pycharm 2017.1.3(in my computer), the easiest way is to open Settings->Tools->Terminal and check Shell integration and Activate virtualenv options.

image


For conda virtual environments on Windows, make sure your batch file is NOT named activate.bat as this will cause a conflict with the conda activate command, resulting in a recursive calling of the batch file.

What works for me is the following Shell path:

"cmd.exe" /k ""C:\FullPathToYourProject\activate-env.bat""

And in the activate-env.bat file:

call activate myenvname

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.

More info here.


On Mac it's PyCharm => Preferences... => Tools => Terminal => Activate virtualenv, which should be enabled by default.


On Windows, if you have already have the virtualenvironment eg. 'myvenv' located within the project root, you can activate it from the terminal as below:

.\myvenv\Scripts\activate

Calling the activate from the virtualenv you desire to activate, activates the virtualenv.

You know it is activated when you see the change:

C:\Projects\Trunk\MyProject>

to

(myvenv)C:\Projects\Trunk\MyProject>

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to virtualenv

How to setup virtual environment for Python in VS Code? Conda version pip install -r requirements.txt --target ./lib What is the purpose of "pip install --user ..."? What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc? ImportError: No module named 'encodings' how to specify new environment location for conda create Use virtualenv with Python with Visual Studio Code in Ubuntu Is it ok having both Anacondas 2.7 and 3.5 installed in the same time? How to uninstall a package installed with pip install --user Unable to install boto3

Examples related to pycharm

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website Pycharm/Python OpenCV and CV2 install error Import numpy on pycharm Global npm install location on windows? Pycharm and sys.argv arguments PyCharm error: 'No Module' when trying to import own module (python script) Using (Ana)conda within PyCharm Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?