Trying to activate venv in PyCharm project with git - python

I've been trying for days to get a virtual environment for my Python project set up in PyCharm. I've seen a bunch of stuff online, but nothing seems to work for me.
Before I start anything, I run which python in my git bash terminal, which returns:
//asc/fs/homedir/<my_account>/pycharm/<repo_name>/Scripts/python
Then, when I try to officially activate the venv, I run source ./venv/Scripts/activate, which promptly fails with error:
bash: basename: command not found
()
After I do this, I lose the little tag at the end of my bash terminal dirpath that normally shows the current git branch I'm on. I don't see (venv), which seems to be the expected behavior based on other stackoverflow posts. There is nothing appended to the current directory path of my terminal.
I can no longer run a number of standard bash commands. Running which python yields
bash: which: command not found
()
Is this some sort of PATH issue? Am I successfully activating the venv at all? (What is the '()' that shows up after every command?)

Supposedly this is an issue with pip on NETWORK drives.
I fixed the issue by moving my virtual environment to my native C: drive, and then went through the normal config process-
set my PyCharm Python interpreter to this NEW venv in my C: drive
updated my PyCharm run/debug configuration to use this new interpreter
restarted terminal
installed all the necessary deps with pip
Good to go! (now I can run pytest + other commands on this local project)

Related

System crashes each time i run python command in Terminal, how to get rid of /opt/miniconda3/bin/python?

please I need your help here!
My system crashes each time i run a python command in terminal. When i run something like python app.py, my Mac will crash and bounce, and reset.
In Terminal,
When i run python -V, it returns Python 3.7.6,
When i run python3 -V, it returns Python 3.8.5
When i run which python, it returns /opt/miniconda3/bin/python.
A moment ago, i was trying to build a standalone app, and turned on virtualenv. However no matter how hard i tried, i failed. Then i deleted the virtualenv folder in the app folder.
Perhaps during the development processes, in Visual Studio Code, i accidentally "linked" the virtualenv with the python interpreter 3.7 (/opt/miniconda3/bin/python), which was set as the default python system long ago (i can't even recall when and how). After the virtualenv folder deletion, i remember the interpreter had the word "cached" in the front of the python version. Somehow i turned on and off this and that, and restarted the app, i have get rid of the word "cached". But the system still crashes .
My Mac crashes now every time i run a python command in Terminal. Please help!
i even have tried update conda update conda, it says no such directory,
ofcoruse i then tried update miniconda, same answer.
You should remove it from your path.
To do so, check for the miniconda3 entry in the file named ~/.bashrc, ~/.bash_profile, and /etc/profile file and comment out the line:
export PATH=/opt/miniconda3/bin:$PATH
by preceding it with the # character.

Can't run Venv in VsCode

For the last 3 days, I have been trying to set up virtual Env on Vs Code for python with some luck but I have a few questions that I cant seem to find the answer to.
Does Vs Code have to run in WSL for me to use venv?
When I install venv on my device it doesn't seem to install a Scripts folder inside the vevn folder. Is this out dated information or am I installing it incorrectly. I am installing onto Documents folder inside my D: drive using python3 - m venv venv. The folder does install and does run in WSL mode but I am trying to run it in clear VsCode so I can use other add-ons such as AREPL that doesn't seem to like being ran in WSL.
For extra context I have oh-my-ZSH set up and using the ubuntu command line on my windows device. Any information will be helpful at this point because I am losing my mind.
venv folder in side D: drive
result
If you have the python extension installed you should be able to select your python interpreter at the bottom.
You should then be able to select the appropriate path
Run Set-ExecutionPolicy Unrestricted -scope process before activating virtual environment.
All the best
You don't have to create a virtual environment under WSL, it will work anywhere. But the reason you don't have a Scripts/ directory is because (I bet) you're running VS Code with git bash and that makes Python think you're running under Unix. In that case it creates a bin/ directory. That will also confuse VS Code because the extension thinks you're running under Windows.
I would either create a virtual environment using a Windows terminal like PowerShell or Command Prompt or use WSL2.

Auto activate virtual environment in Visual Studio Code

I want VS Code to turn venv on run, but I can't find how to do that.
I already tried to add to settings.json this line:
"terminal.integrated.shellArgs.windows": ["source${workspaceFolder}\env\Scripts\activate"]
But, it throws me an 127 error code. I found what 127 code means. It means, Not found. But how it can be not found, if I see my venv folder in my eyes right now?
I think it's terminal fault. I'm using Win 10 with Git Bash terminal, that comes when you install Git to your machine.
This is how I did it in 2021:
Enter Ctrl+Shift+P in your vs code.
Locate your Virtual Environment:
Python: select interpreter > Enter interpreter path > Find
Once you locate your virtual env select your python version:
your-virtual-env > bin > python3.
Now in your project you will see .vscode directory created open settings.json inside of it and add:
"python.terminal.activateEnvironment": true
don't forget to add comma before to separate it with already present key value pair.
Now restart the terminal.
You should see your virtual environment activated automatically.
Actually the earlier suggested solutions didn't work for me, instead I added the following in my settings:
"settings": {
"python.terminal.activateEnvInCurrentTerminal": true,
"python.defaultInterpreterPath": "~/venv/bin/python"
}
Of course replace the defaultInterpreterPath (used to be pythonPath) setting with your own path (so don't copy/paste the second line).
You don't need this line at all. Just remove it and switch your Python interpreter to point to the one within your venv. Here's a relevant documentation (italicized emphasis mine):
To select a specific environment, use the Python: Select Interpreter
command from the Command Palette (Ctrl+Shift+P).
... and
opening a terminal with the Terminal: Create New Integrated Terminal
command. In the latter case, VS Code automatically activated the
selected environment.
Once you switch the interpreter VS code should create a .vscode folder within your workspace with a settings.json indicating the python interpreter. This will give VS code the direction of where to locate the venv.
There is a new flag that one can use: "python.terminal.activateEnvironment": true
my scenario was pretty much the same. I am running VSCode on Windows, wanting to used git bash as my default Terminal but after the venv got created, it was doing some weird stuff when a Terminal would open where it couldn't find the correct python interpeter in the venv/Scripts folder even though I did ctrl-shift-p a bunch of times to reset it to the python.exe there. I also wanted to make sure the activate script was run on Terminal open. I just couldn't get the debugger to work right and it kept complaining that it could not find the python interpreter, so I basically couldn't debug at all.
So for anyone who is having weird stuff happen trying to use a Git Bash Terminal in VSCode in Windows related to a python project using a virtual env, here is what I found out;
I noticed that when I opened a new Git Bash Terminal, and looked at the $PATH variable to make sure it could find the interpreter in the venv, the path to the venv/Scripts folder would be prepended to the $PATH, but not with linux path separators like everything else in $PATH but with a Windows style path;
echo $PATH
C:\Users\blah\Documents\blah\Stock-down\Dev\this_api\venv/Scripts:/c/Users/blah/bin:/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/mingw64/bin:/usr/bin:/c/Users/blah/bin:/c/Program Files/Go/bin:/c/Python39/Scripts:
So whenever I would try to debug, or just even run which python, It would get confused and thought the interpreter was in here;
which python
C:\Users\blah\Documents\blah\Stock-down\Dev\this_api\venv/Scripts/C/Users/blah/Documents/blah/Stock-down/Dev/this_api/venv/Scripts/python.exe
I ran the "printenv" command in the Terminal to see what env vars were getting set and why the venv interpreter path was getting messed up. And I found a env var I didn't know existed - VIRTUAL_ENV. But I didn't know how it was getting set or where it came from. After some pain, and hunting around I found it - when you run "python -m venv venvname" to create the virtual env in the project folder, as you know, it creates the activate (and activate.bat for windows) scripts in the ./venv/Scripts folder. Inside these files this VIRTUAL_ENV variable is not only exported, but but prepended to the $PATH variable on Terminal open with the "/Scripts" folder name added in linux path style. The problem with is that it sets the VIRTUAL_ENV value with windows type path - I know its painful and wrong to do this, but I just changed it to what Git Bash is expecting, see below;
#unset irrelevant variables
deactivate nondestructive
#VIRTUAL_ENV="C:\Users\blah\Documents\blah\Stock-down\Dev\this_api\venv"
VIRTUAL_ENV="/c/Users/blah/Documents/blah/Stock-down/Dev/st_api/venv"
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/Scripts:$PATH"
export PATH
Now when a new Git Bash Terminal is opened it prepends the venv/Scripts path correctly to $PATH;
echo $PATH
/c/Users/blah/Documents/blah/Stock-down/Dev/st_api/venv/Scripts:/c/Users/blah/bin:/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/mingw64/bin:/usr/bin:/c/Users/blah/bin:/c/Program Files/Go/bin:/c/Python39/Scripts:
I also made a copy of the executable python.exe in the ./venv/Scripts dir and just called it "python" and now the command "which python" works and I can debug fine. I still set ctrl-shift-P when I choose the interpreter in VSCODE to "python.exe" when I just use "find" during the selection.
For more information on VIRTUAL_ENV var, see this doc -- python venv docs
It feels like jumping through a bunch of hoops I know, but this way I can open a new Git Bash Terminal, have the activate script run correctly on Terminal Open, debug, and operate normally without having to float between Git Bash AND WSL Ubuntu AND Powershell, etc.
My environment started to activate automatically after the advice from this article
When you create a new virtual environment, a prompt will be displayed
to allow you to select it for the workspace. This will add the path to
the Python interpreter from the new virtual environment to your
workspace settings. That environment will then be used when installing
packages and running code through the Python extension. For examples
of using virtual environment in projects, see the Python, Django, and
Flash tutorials.
My solution was to create /.vscode/settings.json manually
Here is the tree;
├───django
│ ├───.vscode
│ │ ├───settings.json
I created /.vscode/settings.json then added this code in settings.json (I am using windows so I used double backslash for path location otherwise it gives unicode error, and don't copy paste this, find your own .virtualenvs)
{
"python.defaultInterpreterPath": "C:\\Users\\Talha\\.virtualenvs\\django-okd21pq9\\Scripts\\python.exe"
}

Module not found error in VS code despite the fact that I installed it

I'm trying to debug some python code using VS code. I'm getting the following error about a module that I am sure is installed.
Exception has occurred: ModuleNotFoundError
No module named 'SimpleITK'
File "C:\Users\Mido\Desktop\ProstateX-project\src\01-preprocessing\03_resample_nifti.py", line 8, in <module>
import SimpleITK as sitk
I installed the module using
sudo pip install SimpleITK
I know that it was installed because I was getting a similar error when I ran the code through the command line, and it was fixed by doing the above. I don't understand why VS code does not recognize that
After installing a new module via pip reloading vscode may work if vscode doesn't recognize it. To do this, make sure that the module is installed inside the virtual environment by creating and activating a virtualenv:
python3 -m venv env
source env/bin/activate
Make sure to use the correct way of installing a module with pip:
python3 -m pip install {new_module}
Replace the string "{new_module}" with your module name. After that, make sure to reload vscode by clicking Ctrl+Shift+P, and selecting Reload window.
Now vscode will know the new module and autocompletion works.
sudo pip install is most likely installing globally into a Python interpreter that is different than the one that you have selected in VS Code. Please select the Python interpreter you want to use and then install explicitly using that interpreter (if you're not using a virtual environment then use something like /path/to/python -m pip install SimpleITK, although I strongly recommend using a virtual environment and to not install packages globally).
In Mac, correctly selecting the Python Interpreter worked for me:
From within VS Code, select a Python 3 interpreter by opening the Command Palette (⇧⌘P), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):
No interpreter selected
The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don't see the desired interpreter, see Configuring Python environments.
Source :VS Code Select Interpreter
This error: your vscode use other python version. This solution change vscode use current python.
In terminal find current python version:
py --version
In vscode Press Ctrl+Shift+P then type:
Python: Select Interpreter
Select current python version
I ran into this problem with VSCode and resolved it by setting my Python interpreter within VSCode to the same as the one in my system path (type "echo %PATH%" on Windows and look for Python) via the process here: https://code.visualstudio.com/docs/python/python-tutorial#_select-a-python-interpreter
There are a lot of proposed answers that suggest changing the launch.json or the settings.json file. However, neither of these solutions worked for me.
My situation:
Is Python environment selected? yes
Does the Terminal recognize Python environment? yes
Can I run the Python code from the activated Terminal? yes
Does the code run w/o error when I use "Start Debugging"? yes
Does the code run when I click "Run Code"? no
The only solution that worked for me is to:
Open Windows Terminal (or cmd)
Activate environment: conda activate <environment_name>
Open Visual Studio Code from Terminal: code
Then, "Run Code" (#5) works without any issues.
Source:
"module not found error" in VS Code using Conda - l3d00m's answer
Faced similar issue and here is how I fixed it. Remember that there are multiple ways to run your code in VS code. And for each way you may end up with different interpreters and environments. For example:
1. Creating virtual env and installing libraries
In my case I opted into creating virtual environment and doing so outside of VS Code using command prompt:
python -m venv .plotting_test
Following that I activated it:
.plotting_test\Scripts\activate.bat
Following that I installed additional libraries:
python -m pip install matplotlib
Following that I made sure to see it was all installed ok:
python -m pip list
And I also checked where for current directory:
cd
2. Point VS Code & VS Code Code Runner to virtual environment
Opened vs code, closed previous workspaces, opened new folder, created test.py as I was starting new. Pressed ctrl + shift + p. Selected ```Python: Select Interpreter``:
Followed by + Enter interpreted path
Navigated to directory from last step from section 1. Found my virtual environment folder created in step one and pointed VS code to that version's python.exe in Scripts:
Verified I am pointed to such:
Saved as workspace so that I can create default workspace settings for this project:
In workspace settings files defined paths to my virtual environment created n step 1 for workspace interpreter & CODE RUNNER(!):
"settings": {
"python.defaultInterpreterPath": "C:/Users/yyguy/.plotting_test/Scripts/python.exe",
"code-runner.executorMap": {"python": "call C:/Users/yyguy/.plotting_test/Scripts/activate.bat && python -u"}
}
}
Reloaded window just to make sure (ctrl + shift + p) = "Developer: Reload Window"
Now run code and run python file should be execute under your specified envs:
Try running pip list in VS Code to check if the module is installed, next check if your python version is correct/supports that version of SimpleITK. It may be a problem with the python interpreter that you are using for VS Code (ie. the module may be installed on a different python instance than the one your VS Code is using)
Is Python environment selected?
Does the Terminal recognize the Python environment?
Can I run the Python code from the activated Terminal?
Does the code run w/o error when I use "Start Debugging"?
if the answer to the above is "yes."
Then,
Try running the Code using the option "Run python file in terminal" (in code runner extension). And assign a new shortcut for that for future use...
How to fix module not found error in Visual Studio code?
To Solve VSCode ModuleNotFoundError: No module named X Error Make sure you are running from the package folder (not from package/module ) if you want import module. calculations to work. You can also set the PYTHONPATH environment variable to the path to the package folder.
Once you have created a virtual environment, and installed your required packages in that environment, close VS code. For Windows platform, open command prompt and navigate to the folder where your virtual env folder is created. And then launch VS code from there using the command code .
For ex: My virtual env name is .imgenv, and its inside C:\py_stuff\projects
So, I navigate to C:\py_stuff\projects and then type code .
Now, your VS code should recognize the packages !
I just ran into the same issue. I found that if I selected all text before shift enter the script would compile as a file instead of as a single line.
I had the same problem. I bet you have a shebang statement at the top of your file.
If you do.
Visual Studios settings
Under "Code-runner->Code-runner: Respect Shebang" section or just do a search for "Code-runner: Respect Shebang"
Uncheck weather to respect Shebang to run code.
Now it will run under the virtual environment and find the modules that you installed using pip! :)
I struggled with this for a very long time, and had tried almost every other answer. I wasn't using pip, so that wasn't the issue. But still VS Code wasn't finding the modules that were installed in the Selected Interpreter.
Ultimately it came down to old conflicts that existed because I switched to miniconda, and VS Code was still looking for anaconda3.
I completely wiped VS Code and its associated files (cache, preference files, etc.) from my machine (some instructions), and installed a clean version.
This now syncs as expected with miniconda.
If you have different python versions installed, be sure you install module with right one.
python -m pip install <module>
or
python3 -m pip install <module>
Run your environment from a directory not in the users directory. I solved my problem running my environment from C:\Code\ProjectA\
I discovered my problem by running:
IMPORT os
Mycwd = os.getcwd()
PRINT(Mycwd)
.venv/Lib/SitePackages is the default directory where Vscode looks for Modules.
This directory is automatically created on creating .venv via the command Pallete.
External modules installed via pip are placed in this directory by default.
Place self created modules inside this folder manually.
For mac users
In the terminal check which python you are using by command which python. It will give you the path of the python interpreter path. After that type cmd shift P and type Python: Select interpreter.
After that select + Enter interpreter path and paste the path which you got after running the command which python.

running a virtualenv python under Xcode

So far I've been able to work with Python 3 and Xcode 5.1.1 by editing the scheme, pointing the Run executable to python3 and then adding some arguments as in the following picture:
But now I would like to work with isolated Python environments through virtualenv. I can do this through the terminal, as I just have to type workon pydev where pydev is my Python environment. But I have no idea of how to modify my Xcode configuration so that I can run within a Python environment. Is there an environmental variable or something I can set to make this happen?
UPDATE
So I have a partial answer but I still can't make it work on Xcode. I created a simple bash script:
#!/usr/bin/env bash
source ~/.bash_profile
workon pydev
python3 src/__main__.py
The source is needed because otherwise the workon command doesn't work (another file provided by the virtualenv package is sourced inside .bash_profile. I can run the script in the Terminal, but the problem now is that Xcode doesn't like it:
Xcode cannot run using the selected destination.
Choose a destination with a supported architecture in order to run on this system.
I solved it, so you have to add the following pre-action to Xcode.
The source is needed because otherwise the workon command doesn't work (another file provided by the virtualenv package is sourced inside .bash_profile.

Categories