PyCharm Terminal - use Git Bash - python

Goal: use Git Bash as Terminal in PyCharm.
How can I have a normal Bash with Git integrated Terminal in PyCharm?
File path for Git Bash: C:\Users\me\AppData\Local\Programs\Git\git-bash.exe --cd-to-home.
I apply Git Bash in PyCharm Settings:
However, when I click New Session (new Terminal +), it launches as a Window:

You are pointing at git-bash.exe, which is wrong. You should point at bash.exe which is located inside the bin folder. So your Shell path should be:
"C:\Users\<username>\AppData\Local\Programs\Git\bin\bash.exe" --login
using
"C:\Users\<username>\AppData\Local\Programs\Git\bin\sh.exe" --login
would also work. Also works without --login. Make sure the " are there.

Related

VSCode conda activate base giving CommandNotFoundError

I have Anaconda and Visual Studio Code installed on my computer. My default terminal for VS Code is Git Bash. When I open a new terminal in VSCode, it immediately runs the following commands:
C:/Users/ethan/AppData/Local/Continuum/anaconda3/Scripts/activate
conda activate base
The second of these commands gives the following error:
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
If using 'conda activate' from a batch script, change your
invocation to 'CALL conda.bat activate'.
I have tried running conda init bash and conda init --all both inside the VSCode terminal, and inside Git Bash. It handles that command fine, but it doesn't solve my problem. I don't know if the second line of the error applies to me, but even if it did, I don't know how to change the command being called because it is done automatically by VSCode. This error occurs every time I launch a terminal in VSCode (even if I don't have any python files present in my workspace), and it happens both when I launch VSCode from the launch button in Anaconda Navigator and when I launch VSCode by itself.
I had the same issue. For me, easily resolved by launching VSC from the conda window.
Specifically, open your cmd prompt (for me, Anaconda Prompt), activate the environment using 'conda activate [envname]'. Then just run the command 'code'. This will launch VS Code with the activated environment and associated variables. From there, the debug works as expected.
I had the same issue, I've fixed it by adding the Python.CondaPath in settings.
Press Ctrl + Shift + P and select Terminal Configuration. Search for python.conda, and paste your conda path for example. C:\ProgramData\Anaconda3\Scripts\conda.exe
This will fix your issue.
In VS code settings, search for "terminal.integrated.shellArgs.windows", then click "Edit in settings.json". For me, this opened "%APPDATA%\Code\User\settings.json".
I set "terminal.integrated.shellArgs.windows": "-i -l" and this fixed it for me. My file:
{
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": "-i -l"
}
Since conda activate command would cause CommandNotFoundError, use source activate command instead. It works the same.
I had the same issue. I got the following error:
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
If using 'conda activate' from a batch script, change your invocation to 'CALL conda.bat activate'.
To initialize your shell, run
$ conda init <SHELL_NAME>
Currently supported shells are:
- bash
- cmd.exe
- fish
- tcsh
- xonsh
- zsh
- powershell
See 'conda init --help' for more information and options.
IMPORTANT: You may need to close and restart your shell after running 'conda init'.
I solved it by manully run
source activate base
and Ta-da~ DONE!
This trick is simple, while needed every time you open a new git-bash terminal in VSCode.
This worked for me go to setting and search for
terminal.integrated.shellargs.windows
then choose Command Prompt like this
I had exactly the same error as you. I solved it with a tip from a Python course in Udacity
Open Git Bash command line (NOT within VSC terminal) and go to your home folder, e.g., /c/Users/arman. Then run the following two commands but replace [YOUR_PATH] with your Anaconda installation folder
echo 'export PATH="$PATH:[YOUR_PATH]:[YOUR_PATH]/Scripts"' >> .bashrc
echo 'alias python="winpty python.exe"' >> .bashrc
For example in my case, as I have miniconda, I executed:
echo 'export PATH="$PATH:/c/Users/arman/Miniconda3:/c/Users/arman/Miniconda3/Scripts"' >> .bashrc
echo 'alias python="winpty python.exe"' >> .bashrc
After this executing those lines, i.e., creating the .bashrc file, then run:
source .bashrc
Afterwards, open VSC and try running or debugging a python program. It worked for me!
I solved this issue by using Powershell. Start the Powershell as Administrator and then type
set-ExecutionPolicy RemoteSigned
Say yes if it asks a confirmation. Now, VSCode debugger option can be used with Python.
When I changed my default terminal in VS Code to cmd.exe I got conda to work properly for me.
None of these worked for me. In the end I changed my default VScode terminal to cmd instead of Powershell in the terminal default settings which was None for Windows. I had already added conda.exe to my path and changed the permissions as described above.
For some reason the activate.bat file was now found in the path which activated my virtual env.
This answer is dedicated to Windows 10/11 users, based on PowerShell VS Code integrated terminal, and assumes using miniconda but the same holds for conda under the previous environment.
From the start menu type or search for Anaconda Powershell Prompt then right-click to open its file location. You should see the PowerShell shortcut. Right-click and open properties. In the target bar try to find C:\Users\username\miniconda3\shell\condabin\conda-hook.ps1' ; PowerShell script (.ps1). Using file explorer locate C:\Users\username\miniconda3\shell\condabin. Copy the content of that script.
In the default Documents folder create a folder named WindowsPowerShell if not exists and edit or create a new Microsoft.VSCode_profile.ps1 script in it. Lastly, paste by appending the content of the former script.
You could do the same for the external PowerShell but the script under the path C:\Users\username\Documents\WindowsPowerShell should be named Microsoft.PowerShell_profile.ps1.
In other words, the PowerShell profile script enables the creation of aliases and defining functions that load every time you launch the shell. However, the changes take effect after restarting VS Code and/or PowerShell.

Anaconda and Git Bash in Windows - conda: command not found

I've installed Anaconda and set Path environment variable to C:\Anaconda3; C:\Anaconda3\Scripts.
Then I try to run in Git Bash
conda install python
But there is an error message "bash: conda: command not found". I would like to know why.
To be able to run conda on gitbash you need to add it to the path. Many times I've seen that's done by default - as shown in the setup for this workshop. If it doesn't, as it seems your case, then you can run their setup directly by running:
. /c/Anaconda3/etc/profile.d/conda.sh
After running that you should be able to run conda commands.
To keep this setup permanently you can add such line on your .profile or .bashrc file (read more about their differences). A way of doing so is running the follwing:
echo ". /c/Anaconda3/etc/profile.d/conda.sh" >> ~/.profile
You may encounter problems if the path where Anaconda was installed contains spaces (e.g., C:\Program Files). In that case you would need to change the anaconda location or edit conda.sh script with something like:
sed -e '/^_CONDA_EXE=.*/a alias myconda="${_CONDA_EXE/ /\\\\ }"' \
-e 's/\$_CONDA_EXE/myconda/g' /c/Program\ Files/Anaconda3/etc/profile.d/conda.sh > conda_start.sh
This sed command inserts a new alias definition myconda which changes the anaconda path from Program Files to Program\ Files so bash doesn't stop with an error like this one:
bash: /c/Program: No such file or directory
The second sed command replaces the _CONDA_EXE variable by the new alias created.
Since the above doesn't modify the file provided by anaconda, you will need to update your .profile file to load the file we've just created, conda_start.sh, instead.
First, you need to move to the directory where conda is located.
(some path such as C/Anaconda3/Scripts or ../miniconda3/Scripts or anaconda3/bin)
then, open the terminal.
(or, if you use Windows and can't find where the conda is, try moving to directory such as C:\Users\User_Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit) and open the Anaconda prompt.)
Then, do this:
conda init
or something like
conda init bash
if you use Mac OS:
conda init zsh
will work well.
if you wanna use different shell,
conda init [shell_name]
[shell_name] can be: bash, cmd.exe, fish, powershell, tcsh, xonsh, zsh, etc.
use conda init --help for more info.
Joining #dvdgc13. In my case, I fixed the problem by adding
. C:/Users/user/Anaconda3/etc/profile.d/conda.sh
to my .bash_profile.
I tried to do the same thing as you did but I couldn't get it to work. starriet had the working answer but I am going to make it easier for everyone else reading. You can directly open command windows with explorer instead of struggling with paths.
Find your Anaconda3 folder with Windows Explorer This could be a user install where would be in your user folder such as "C:/Users/your_name/Anaconda3".
Shift + Right Click on the explorer and click on "Open PowerShell Windows Here". Note: you can just click "Git Bash" and you open Bash instead which makes no difference to the command.
Type in "conda init" in the PowerShell window. This works even if you don't have the right paths because the command line looks for the right exe in the current dictionary. If you scroll down in the explorer, you should be able to find it.
My PowerShell window would look a little different than yours because of my prompt but it makes no difference.
Exit the PowerShell and open Git Bash. Type "conda" to confirm that things work.
For MAC users, do this:
$ echo ". /usr/local/anaconda3/etc/profile.d/conda.sh" >> ~/.bashrc
$ source ~/.bashrc
I tried many ways, but they are incomplete until I run the following commands:
Go to the path of anaconda3 is C:\Users\USER_NAME\anaconda3 and open commend line over there and print the following: (YOUR_PATH = C:\Users\USER_NAME\anaconda3 )
echo 'export PATH="$PATH:[YOUR_PATH]:[YOUR_PATH]/Scripts"' >> .bashrc
echo 'alias python="winpty python.exe"' >> .bashrc
If Git bash is opened, close it and reopen it again and type the following to make sure anaconda and python work without problems:
conda --version
python -- version
If you see the versions are printed, everything works well.
In my case conda command was recognised in cmd, but not in bash. I used conda init bash instead of simple conda init in cmd.
This command modified the .bash_profile file, which was residing in my C:\Users\xyz directory, and added the following code in it
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
eval "$('/C/Users/Saifullah/miniconda3/Scripts/conda.exe' 'shell.bash' 'hook')"
# <<< conda initialize <<<
now it is working in bash terminal too.

ls and cd commands not working with Cygwin

I am trying to use Cygwin to run my first python program. I downloaded python and Cygwin. Within the Cygwin terminal I ran the command: "which python" to confirm that the terminal could find python. However when I attempt to cd into my Desktop for example, I get "-bash: cd: Desktop: No such file or directory". When I try to do an ls, it simply returns an empty line. For some reason "pwd" works normally.
I am having a problem similar to the one here: Cygwin ls command not found
However changing the environmental variables has no effect (even after I closed and repopened the terminal window).
Make sure C:\cygwin64\bin or its equivalent is set as a path variable.
Run mintty.exe as administrator and enter: mkpasswd -l -p "$(cygpath -H)" > /etc/passwd
Close mintty.exe and access it again through the Windows shortcut 'Cygwin64 Terminal'. This is auto-generated during setup. The shortcut target should be set as the path to the bin which contains mintty.exe C:\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico -.
Hope this helps!

how to use python to do a series of commands in terminal

I put the following in my python_go.py
import os
os.system("cd some_dir") # This is the directory storing an existing virtual environment
os.system(". activate") #because I want to activate the virtual environment
os.system("cd another_dir") #this the directory I can start my work
I hope I can run the python_go.py, it can do the work mentioned above.
But when I run it, seems it can only do the first step, the rest of it, e.g. . activate seems not working.
Can someone tell me how to do it? Thank you!!
Most probably you don't have to change to some_dir to source activate so saving these lines
. some_dir/activate
cd another_dir
as, let's say go.sh and doing
. go.sh
has the same effect
If you're relying to os.system(". activate") to work if it's in the directory some_dir that won't work because the current directory won't persist across calls to os.system().
You're going to be better off calling a shell script that aggregates all three of the commands you want to do and execute that once from the python script.
Otherwise you want to set up the environment for the parent python process using os.chdir() before calling os.system on the activate call. Also, the os.system(". activate") call won't do what you want because the "dot space" notation will load information into a shell that's going to go away when the os.system call finishes.
Edited (to your followup comment):
Your shell script should look like this (do_activate.sh):
cd some_dir
. activate
cd another_dir
and the python code like this:
os.system("db_activate.sh").
Keep in mind that whatever environment variables were saved by ". activate" won't persist after the os.system call.
Your code does nothing. os.system() starts a new shell for each command i.e., all os.system() calls have no positive effect: cd and . activate may have effect only on the current shell (and possibly its children).
If all you want is to activate a virtualenv in the current shell then you should use a shell command:
$ . some_dir/activate && cd another_dir
Note: the command has effect only on the current (running) shell (and its descendants).
virtualenvwrapper provides several hooks that allows to execute commands before/after activating a virtualenv e.g., you could put cd another_dir into $VIRTUAL_ENV/bin/postactivate then it is enough to run:
$ workon <virtualenv-name>
to activate virtualenv-name virtualenv and run all the hooks (cd another_dir in this case).
You probably want to install virtualenvwrapper which does what you want:
workon envname will source the file and activate the virtualenv.
You can then do setvirtualenvproject in the desired directory and you'll automatically go to the directory where the project is located. You only need to do this command once as it'll then happen automatically from then on.

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?
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
Auto virtualenv is supported for bash, zsh, fish, and Windows cmd. You
can customize your shell preference in Settings (Preferences) | Tools
| Terminal | check Activate virtaulenv
you also need to make sure to have the path of virtual environment path included in the content root folder of your project structure. You can go to settings (preference) | project | Project Structure | if your environment is not included in the project directory.
***Old Method:***
Create a file .pycharmrc in your home folder with the following contents
source ~/.bashrc
source ~/pycharmvenv/bin/activate
Use your virtualenv path as the last parameter.
Then set the shell Preferences->Project Settings->Shell path to
/bin/bash --rcfile ~/.pycharmrc
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""
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.
Somehow a small trick worked for me. All you gotta do is change the default terminal from Power shell to CMD.
Open pycharm --> Go to Settings --> Tools --> Terminal
Change the Shell Path to C:\Windows\system32\cmd.exe from PS
Check the Activate virtualenv checkbox
Hit apply and open new terminal
It's 2021 you don't need to specify the file path or add the environment variable.
Update: It's 2022 and I run into the same issue
Fix: Follow the above steps and in addition, make sure you have selected the Your virtual env python.exe as your project python interpreter, and that's it
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.
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.
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
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.
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.
On Mac it's PyCharm => Preferences... => Tools => Terminal => Activate virtualenv, which should be enabled by default.
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>
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
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.
I had the same problem with venv in PyCharm. But It is not big problem!
Just do:
enter in your terminal venv directory( cd venv/Scripts/ )
You will see activate.bat
Just enter activate.bat in your terminal after this you will see YOUR ( venv )
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.
If your Pycharm 2016.1.4v and higher you should use
"default path" /K "<path-to-your-activate.bat>"
don't forget quotes
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>
I had the similar problem of not having venv activated in pycharm terminal (Pycharm version 2021.2.2). Just simply follow the steps below.
Go to "settings -> tools -> terminal" then at the bottom of that window check if "Activate virtualenv" is having a tick or not, if not then make sure that box is ticked.
Then in the middle part of that window check the the shell path is set to "cmd.exe" or not, if not then set it to "cmd.exe" (it will have it's path associated with it so no need to do anything just click on "cmd.exe" from the drop down list) then click on "apply" button below and click "ok".
Now it's done, just close your opened terminal and re-open it. You will see "venv" in front of your project path.
P.S: Don't mind the double quotes in my answer they are just for highlighting the texts, nothing more.
Had the same issue, this is how I solved it:
All you gotta do is change the default terminal from Power shell to CMD.
Open pycharm --> Go to Settings --> Tools --> Terminal.
Change the Shell Path to C:\Windows\system32\cmd.exe from PS.
Check the Activate virtualenv checkbox.
Hit apply and open new terminal.
If you're using windows with wsl2, the only thing that worked for me (November 2022) was:
go into Pycharm terminal definition
paste:
wsl.exe -- bash --rcfile <(echo '. ~/.bashrc; source <path-to-your-virtial-env>/bin/activate')
inside the 'Shell path' box.
Then every time you open the terminal the virtual environment would be activated.
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$
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.
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
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.
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>
One option you have when you enter the terminal >
Run > Debug > Edit Configurations
select the appropriate conda environmnent..
Also when you create a new project - it asks to configure this location.
As you can see, python interpreter is located in venv/bin/python. If you go to this folder, you will see all libraries listed in there
Sooo... as you will think, you use python command with it's path - that means in project path, for example
./venv/bin/pytest
Windows Simple and Easy Solution:
In Pycharm inside the Projects menu on the left there will be folders.
Find the Scripts folder
Inside there you'll find activate.bat
Right click on activate.bat
Copy/Path Reference
Select Absolute Path
Find the Terminal tab located in the middle at the bottom of Pycharm.
Paste it into the terminal console and press enter
If you did it right the terminal path will have brackets (venv) around the name of the folder you activated.
Before: "PS C:\"
After: "(venv) C:\"
Note The folder name may be different than yours the important part is the (brackets) :D

Categories