Pycharm unresolved reference in virtualenv - python

When I started a new project in Pycharm using virtual environment, I got an unresolved reference warning message.
But I have installed django to my virtual environment and this code is working correctly.
How can I fix this? I'm using PyCharm 4.5.2 Pro

Open your project in pycharm and follow the step:
click on file(on top) > settings > project interpreter > add local > select virtualenv
OR
Make sure your project is a root directory, make it is the root directory.

I eventually stumbled across a method that worked for me, but I don't know the underlying problem.
Initially I created a virtualenv with PyCharm in the interpreter options. Annoyed that I was having this problem, I deleted it and just created a virtualenv with the virtualenv command, but the problem remained.
Then I went back to the interpreter selector and picked "add local". I navigated to the python binary in the /bin folder of the virtualenv I created and selected it. After this, the unresolved references were fixed.

I think your problem is like mine. I tested import matplotlib in the python shell, and it works, but in Pycharm it shows an error. This is because Pycharm doesn't know the path of site-packages.
To fix this, you can do one of the following:
Add the path of site-packages (for me C:\Program Files\Python 3.5\lib\site-packages) to PATH.
Go to File -> Settings -> Project Interpreter, then choose Python real path instead of venu path.
In your code add the following:
.
import sys
sys.path.append(r"C:\Program Files\Python 3.5\lib\site-packages")
import matplotlib.pyplot as plt
I think it will help you :)

File > Settings > Project > Project Structure
Double Click on the folder link under Content Root, and do OK.

Check your project root directory. Maybe problem in it.
And did you create virtualenv manually or through PyCharm?

Related

VS Code doesn't recognize Python Virtual Environment Packages - It shows red underlines

I installed python virtual env. I use vs code. I imported scrapy in my code and vs code doesn't recognize the module. Actually, it works well when I run it. scrapy crawl tester
Just, vs code shows red underlines that mean "Unable to import scrapy" So this is just vs code issue, not venv or scrapy package install issue.
This code works well and actuallay, scrapy is imported without any issue. This is just vs code issue. Thank you.
You might be able to solve your problem by using CTRL+Shift+P to add "Python: Select Interpreter" to your project.
If you created a virtual environment and activated it as well
type which python on macOS/Linux,
type where python on Windows,
inside the activated terminal session.
(env) userpc#pc:~$ which python
/home/userpc/Desktop/foldername/env/bin/python
In VSCode press Ctrl+Shift+P, under >Select Interpreter paste the location you receive using the former command.
Once done, restart VSCode.
VSCode will also ask you to install pylint in your environment and if it doesn't you can do the same by activating you environment and typing
pip install pylint
inside the activated terminal session.
Ran into the same problem - selected the correct Python interpreter in VS Code, pip installed all the desired Python libraries but import is still underlined in VS Code.
What you need to do
What worked for me is to make sure that the linter that you are using in this VS Code instance (I was using pylint) is from the bin folder of the virtual environment, not somewhere else.
How you can do it
I'll use the absolute path to the desired virtual environment /User/ProjectFolder/env as an example.
To check that you meet the conditions stated in What you need to do, toggle the settings.json file in VS Code by pressing ⌘ + ,:
Make sure that the correct Python interpreter is selected. i.e. "python.pythonPath":/User/ProjectFolder/env/bin/python3.
Make sure that the linter (e.g. pylint) is located in that bin folder, not anywhere else. i.e "python.linting.pylintPath":/User/ProjectFolder/env/bin/pylint, NOT something like "python.linting.pylintPath":/usr/local/bin/pylint.
This means that you have to install your desired linter in the virtual environment.
Hope this helps.
I tried #cleon-w's answer which worked for me. (Thanks Cleon)
I was using pyenv on my Mac M1 (Big Sur) with vscode. vscode could not resolve the
paths to python that the pyenv provides, so I looked within the pyenv scripts to find the absolute paths
to the underlying python and the pylint files.
As #Cleon W says I ensured pylint and python are in the same bin directory.
Then edit VS Code settings.json to point to them directly (bypass .pyenv) and the imports could be found.
settings.json (vscode)
"python.defaultInterpreterPath": "/Users/USERNAME/.pyenv/shims/python",
"python.pythonPath": "/Users/USERNAME/.pyenv/versions/3.9.1/bin/python",
I have similar problem with Django. What solved my problem was:
create .vscode/settings.json file inside root dir for project.
add this json {"python.defaultInterpreterPath": "path to bin directory in root dir for project"}
Ctrl-Shif-P -> Python: Select Interpreter -> select one that said: Use Python from python.defaultInterpreterPath. If it's not in the list, hit refresh (circled refresh button on the top of settings box).

Pylint "unresolved import" error in Visual Studio Code

I am using the following setup
macOS v10.14 (Mojave)
Python 3.7.1
Visual Studio Code 1.30
Pylint 2.2.2
Django 2.1.4
I want to use linting to make my life a bit easier in Visual Studio Code. However, for every import I have states "unresolved import". Even on default Django imports (i.e. from django.db import models).
I presume it is because it is not seeing the virtual environment Python files.
Everything works just fine, but it's starting to get annoying.
The interpreter choices I have are all system versions of Python. It does not seem to see my virtual environment Python at all (it is not in the same directory as my workspace, so that part makes sense).
If I set up the python.PythonPath in the settings.json file, it just ignores it and does not list my virtual environment path as an option. I also tried setting it up in my global Python settings, but it also does not show up.
Is there a quick fix to get it working?
The accepted answer won't fix the error when importing own modules.
Use the following setting in your workspace settings .vscode/settings.json:
"python.autoComplete.extraPaths": ["./path-to-your-code"],
Reference: Troubleshooting, Unresolved import warnings
In your workspace settings, you can set your Python path like this:
{
"python.defaultInterpreterPath": "/path/to/your/venv/bin/python",
}
Alternative way: use the command interface!
Cmd/Ctrl + Shift + P → Python: Select Interpreter → choose the one with the packages you look for:
This issue has already been opened on GitHub:
Python unresolved import issue #3840
There are two very useful answers, by MagnuesBrzenk and SpenHouet.
The best solution for now is to create a .env file in your project root folder. Then add a PYTHONPATH to it like this:
PYTHONPATH=YOUR/MODULES/PATH
And in your settings.json add:
"python.envFile": ".env"
When I do > reload window that fixes it.
Reference: Python unresolved import issue #3840, dkavraal's comment
None of the solutions worked except this one. Replacing "Pylance" or "Microsoft" in the settings.json solved mine.
"python.languageServer": "Jedi"
You need to select the interpreter associated with the virtual environment.
Click here (at the bottom status bar):
And just select the virtual environment you are working with. Done.
Sometimes, even with the interpreter selected, it won't work. Just repeat the process again and it should solve it.
If you have this code in your settings.json file, delete it:
{
"python.jediEnabled": false
}
If you are more visual like myself, you can use the Visual Studio Code configurations in menu File → Preferences → Settings (Ctrl + ,). Go to Extensions → Python.
In the section Analysis: Disabled, add the suppression of the following message: unresolved-import:
I was able to resolved this by enabling jedi in .vscode\settings.json
"python.jediEnabled": true
Reference from https://github.com/Microsoft/vscode-python/issues/3840#issuecomment-456017675
I wonder how many solutions this problem have (or have not), I tried most of the above, nothing worked, the only solution that worked is to set the python language server to Jedi, instead of Microsoft in the settings.json file:
"python.languageServer": "Jedi"
None of the previous answers worked for me. Adding both of the lines below to my settings.json file did, however.
"python.analysis.disabled": [
"unresolved-import"
],
"python.linting.pylintArgs": ["--load-plugin","pylint_protobuf"]
The first line really just hides the linting error. Certainly not a permanent solution, but de-clutters the screen.
This answer gave me the second line: VS Code PyLint Error E0602 (undefined variable) with ProtoBuf compiled Python Structure
Maybe someone who understands Python more than me can explain that one more.
Okay, so 2 years down the line, I have ran into this annoying problem. All I can seen here are some really complicated workarounds. Here are easy to follow steps for anyone else who might just run into this later on:
at the bottom of VS Code where you see the Python version listed, just click there
Select Interpreter windows is going to appear
click on the first option that says "Select Interpreter Path" and navigate to the folder path which has your Virtual Environment
That's all you need to do and avoid tampering with those settings in VS Code which might get very complicated if not handled with caution.
My solution
This solution is only for the current project.
In the project root, create folder .vscode
Then create the file .vscode/settings.json
In the file setting.json, add the line (this is for Python 3)
{
"python.pythonPath": "/usr/local/bin/python3",
}
This is the example for Python 2
{
"python.pythonPath": "/usr/local/bin/python",
}
If you don't know where your Python installation is located, just run the command which python or which python3 on the terminal. It will print the Python location.
This example works for dockerized Python - Django.
I was facing the same problem while importing the project-related(non standard) modules.
Detailed explanation of the problem
Directory structure:
Project_dir:
.vscode/settings.json
dir_1
> a
> b
> c
dir_2
> x
> y
> z
What we want:
Project_dir
dir_3
import a
import y
Here "import a" and "import y" fails with following error:
Import "dir_1.a" could not be resolvedPylancereportMissingImports
Import "dir_2.y" could not be resolvedPylancereportMissingImports
What worked for me:
Appending the top directory which contains the modules to be imported.
In above example add the follwoing "Code to append" in ".vscode/settings.json"
Filename:
.vscode/settings.json
Code to append:
"python.analysis.extraPaths": [dir_1, dir_2]
The solution from Shinebayar G worked, but this other one is a little bit more elegant:
Copied from Python unresolved import issue #3840:
Given the following example project structure:
workspaceRootFolder
.vscode
... other folders
codeFolder
What I did to resolve this issue:
Go into the workspace folder (here workspaceRootFolder) and create a .env file
In this empty .env file, add the line PYTHONPATH=codeFolder (replace codeFolder with your folder name)
Add "python.envFile": "${workspaceFolder}/.env" to the settings.json
Restart Visual Studio Code
To me the problem was related with the project that I was working on. It took me a while to figure it out, so I hope this helps:
Original folder structure:
root/
__init__.py # Empty
folder/
__init__.py # Empty
sub_folder_b/
my_code.py
sub_folder_c/
another_code.py
In another_code.py:
from folder.sub_folder_b import my_code.py
This didn't trigger the intellisense in Visual Studio Code, but it did execute OK.
On the other hand, adding "root" on the import path, did make the intellisense work, but raised ModuleNotFoundError when executing:
from root.folder.sub_folder_b import my_code.py
The solution was to remove the _init_.py file inside the "folder" directory, leaving only the _init_.py located at /root.
This works for me:
Open the command palette (Ctrl + Shift + P) and choose "Python: Select Interpreter".
Doing this, you set the Python interpreter in Visual Studio Code.
None of the answers here solved this error for me. Code would run, but I could not jump directly to function definitions. It was only for certain local packages. For one thing, python.jediEnabled is no longer a valid option. I did two things, but I am not sure the first was necessary:
Download Pylance extension, change python.languageServer to "Pylance"
Add "python.analysis.extraPaths": [ "path_to/src_file" ]
Apparently the root and src will be checked for local packages, but others must be added here.
I am using the following setup: (in Apr 2021)
macos big sur
vscode
Anaconda 3 (for environment)
And I faced this error during starting of the Django.
So, I follow these steps and this error is resolved.
Steps are given in these screenshots:
Open settings (workspace)
Follow this screenshot to open Python Path
Now, click Edit in settings.json
Make path like given in this screenshot /opt/anaconda3/bin/python
5. Now, save this settings.json file.
6. Restart the vscode
Also, intellisense might not work for some time hold on wait for some time and then restart again then vscode reads file for new path.
That happens because Visual Studio Code considers your current folder as the main folder, instead of considering the actual main folder.
The quick way to fix is it provide the interpreter path to the main folder.
Press Command + Shift + P (or Ctrl + Shift + P on most other systems).
Type Python interpreter
Select the path where you installed Python in from the options available.
Changing
Python:Language Server
to 'Jedi' worked for me.
It was 'Windows' initially.
For me, it worked, if I setup the paths for python, pylint and autopep8 to the local environment paths.
For your workspace add/change this:
"python.pythonPath": "...\\your_path\\.venv\\Scripts\\python.exe",
"python.linting.pylintPath": "...\\your_path\\.venv\\Scripts\\pylint.exe",
"python.formatting.autopep8Path": "...\\your_path\\.venv\\Scripts\\autopep8.exe",
Save and restart VS Code with workspace.
Done!
I have a different solution: my Visual Studio Code instance had picked up the virtualenv stored in .venv, but it was using the wrong Python binary. It was using .venv/bin/python3.7; using the switcher in the blue status bar.
I changed it to use .venv/bin/python and all of my imports were resolved correctly.
I don't know what Visual Studio Code is doing behind the scenes when I do this, nor do I understand why this was causing my problem, but for me this was a slightly simpler solution than editing my workspace settings.
In case of a Pylint error, install the following
pipenv install pylint-django
Then create a file, .pylintrc, in the root folder and write the following
load-plugins=pylint-django
I have faced this problem in three ways. Although for each of them a solution is available in the answers to this question, I just thought to put it all together.
First I got an "Unresolved Import" while importing some modules and I noticed that my installations were happening in global pip instead of the virtual environment.
This issue was because of the Python interpreter. You need to select the interpreter in Visual Studio Code using Shift + Ctrl + P and then type Select Python Interpreter. Select your venv interpreter here.
The second issue was: The above change did not resolve my issue completely. This time it was because of file settings.json. If you don't have the settings.json file in your project directory, create one and add the following line in that:
{
"python.pythonPath": "apis/bin/python"
}
This will basically tell Visual Studio Code to use the Python interpreter that is in your venv.
The third issue was while importing a custom Python module or file in another program. For this you need to understand the folder structure. As Python in venv is inside bin, you'll need to specify the folder of your module (most of the time the application folder). In my case it was app,
from app.models import setup_db
Verbally, import setup_db from models.py resides in the app folder.
If you are using pipenv then you need to specify the path to your virtual environment.in settings.json file.
For example :
{
"python.pythonPath":
"/Users/username/.local/share/virtualenvs/Your-Virual-Env/bin/python"
}
This can help.
If someone happens to be as moronic as me, the following worked.
Old folder structure:
awesome_code.py
__init__.py
src/
__init__.py
stuff1.py
stuff2.py
New structure:
awesome_code.py
src/
__init__.py
stuff1.py
stuff2.py
How to avoid warning
Please note that this is just skipping the warning not resolving it.
First of all open visual studio code settings in json and add following arguments after "[python]":{}
"python.linting.pylintArgs": ["--rep[![enter image description here][1]][1]orts", "12", "--disable", "I0011"],
"python.linting.flake8Args": ["--ignore=E24,W504", "--verbose"]
"python.linting.pydocstyleArgs": ["--ignore=D400", "--ignore=D4"]
This has helped me to avoid pylint warnings in VSCode.
I have resolved import error by Ctrl + Shift + P.
Type "Preferences settings" and select the option Preferences Open Settings (JSON)
And add the line "python.pythonPath": "/usr/bin/"
So the JSON content should look like:
{
"python.pythonPath": "/usr/bin/"
}
Keep other configuration lines if they are present.
This should import all modules that you have installed using PIP for autocomplete.

Python works in PyCharm but not from terminal

I recently figured out how to import modules for unittesting in python. As a solution to this, I use:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from Dev.test import someclass
This works fine while running in PyCharm and I get the expected output. However, when I run from terminal I run into an error:
ImportError: No module named Dev.test
I have the init files where they are supposed to be but I'm lost as to why this is working in PyCharm but not from the terminal. I have not changed my path or anything in PyCharm as this code is supposed to be able to run with minimal modifications on other machines. Any idea as to why this is happening and what I might be able to do to fix it?
My folder structure is as follows
-Current
-Dev
-__init__.py
-test
- __init__.py
-someclass.py
-Tests
-__init__.py
-someunittest.py
I have tried running someunittest from the main folder as well as with a complete path but it only works in PyCharm
sys.path.append(os.getcwd()[:os.getcwd().index('Dev')])
I added this to my imports and it seems to have solved the problem. However, this doesn't seem like it would be the right way to do it; it will do for now.
When running a script from within PyCharm, it runs it in an environment with PYTHONPATH set to the list of all the folders that are marked "Sources Root" (with a blue folder icon) in the project explorer.
Outside of PyCharm, PYTHONPATH is not normally set. The first entry in sys.path refers to the current working directory where the script was run from. As long as you run your script with your terminal's working directory as the folder containing Dev, it should be able to find the Dev.test module, regardless of the extra entry added to sys.path.
Once you get the working directory correct, you should be able to remove the sys.path hack.
What #codewarrior has said about the PyCharm setting its own PYTHONPATH is correct. But sys.path didn't have my current working directory. So to get around this problem, I updated my PYTHONPATH (or you can edit sys.path).
Setting PYTHONPATH
export PYTHONPATH=$PYTHONPATH:`pwd` (OR your project root directory)
Updating sys.path
import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')
You can use insert/append based on the order in which you want your project to be searched.
HTH.
Pycharm uses a virtual environment. When you try run your program in your terminal this enviroment isn't active.
You need to build or upload your enviroment Pycharm with your libraries.
cd to the directory project and write in terminal:
source venv/bin/activate
I too have had this issue - and the PYTHONPATH setting set by PyCharm did seem to be the issue.
My alternative (as I was nearly finished writing the code) was to generate a setup.py - and install the classes/structure in my local virtual Python environment.
I would recommend trying out $ pip install . in your source directory. This will install your own packages for your project.
To add to similar answers here, PyCharm is doing some extra config for you before running your script. If adding your sources root to PYTHONPATH doesn't work then examine your run configuration in PyCharm for the script in question, there will likely be some more behind the scenes magic at play.
I had similar problem. I think the problem is that Pycharm modifies PYTHONPATH so before running your script:
cd to the file where python file resides
run export PYTHONPATH=.
run the script
You can also create "main" python file where you set the python path and then call the other modules

Pydev, eclipse and pythonpath problem

I've installed pydev to my eclipse 3.5.2. Everything was working smoothly, create projects, execute, test, autocomplete.
But then I realized that importing modules from /usr/lib/pymodules/python2.6, such as django, causes error "Unresolved import: xxxx". Of course, PYTHONPATH SYSTEM includes the directories I want. What's more, inside package explorer i can c the modules under "System Libs".
I just can't import them :S. Is this a bug? Or I just missing something.
Thanks.
In eclipse you can add django folder in you python path.
Window->Preferences-> PyDev-> Interpreters->Python Interpreter -> Lirararies -> New Folder
And browse till the parent folder of modules you are searching.
If you're using virtualenv you should setup an interpreter using the python build inside.
ie., default python interpreter for th project will be /usr/bin/python
but change it to something like "{project name} python" and point it to your virtual env path. In my case it's ~/.virtualenvs/acme/bin/python
It seems like some sort of cache issue in PyDev... in which case you could try to remove the interpreter, add it again and restart Eclipse.

Unresolved import: models

I'm doing my VERY first project using python/django/eclipse/pydev following this guide
http://docs.djangoproject.com/en/dev/intro/tutorial01/
My only addition is the use of Eclipse/pydev.
I'm getting many errors related to "Unresolved imports". I can remove the errors using "remove error markers" and my site runs perfect (I can browse it) but I want to get rid definitively of this problem since errors pop up again after I removed them.
Any ideas?
EDIT
Using Ubuntu 9.1
Check your pythonpath. You need to include the parent directory of django, usually Lib/site-packages.
I'm on Mac OS X, but all I had to do was to add:
/Library/Python/2.6/site-packages
to my System PYTHONPATH (Found in: Preferences > Pydev > Interpreter - Python)
The equivalent for Ubuntu 10.04 would be:
/usr/lib/pymodules/python2.6
I'm guessing that the equivalent for Ubuntu 9.x could be:
/usr/lib/python2.6/site-packages
If it isn't and you're tired of looking, just upgrade to Ubuntu 10.04 and you should be fine.
I was able to get rid of the import errors executing this cmd
sudo ln -s /usr/lib/pymodules/ /usr/lib/python2.6/pymodules
I was lucky, testing different things I could resolve it but I'm not sure why I have to do this and how I could avoid doing it.
"Unresolved imports" occur when Eclipse/Pydev does not know what you want to import. Check your Pydev settings in the Eclipse preferences > Interpreter Python. Your site-packages folder and things you want to import should be there in the Pythonpath.
Also see http://pydev.org/manual_101_interpreter.html
Even if Lib/site-packages is added to the PYTHONPATH, this problem may happen when using modules from egg packages installed using easy_install. The problem with those, and that might actually depend on the easy_install version, is that by default they don't get installed directly inside Lib/site-packages but rather under a folder containing the full package name and having the .egg suffix. For example: Lib/site-packages/django_celery-3.0.23-py2.7.egg
Each module coming from packages installed as above needs an individual entry in PYTHONPATH. If the packages are installed after PyDev has been installed on the system, the system PYTHONPATH needs to be updated in PyDev. That is done automatically by going to Window -> Preferences -> PyDev -> Select your intepreter -> in the python interpreters panel remove and re-add your current python interpreter (usually, this should be the python executable from the system). Then a PyDev restart (File -> Restart) should solve the "Unresolved import" errors.
If you are facing problem of unused imports then I must say use Eclipse as a IDE as it is providing functionality to remove unused imports by pressing keys ctr+shift+O. Or In Eclipse there is plugin also available which is doing the same thing automatically when you save your code.You can get that plugin from eclipse plugin site easily and free of cost.
In my case of the modules were dependent on setuptools-14.3.1 , which was causing all these problems. After installation of setuptools-14.3.1 rest of the modules automatically resolved.
I was having a single import error when working in PyDEV in eclipse.
I was importing it like
from xyz_module import abc
So I clicked "Ctl + 1" and "select Unresolved import error" in eclipse and it created a class
file in a python file.
It turned out that I had created an application called "xyz_module" and a "xyz_module.py" file (with the same name that is) and this was causing an import error. I changed the python file to a new name and this resolved the error.
I had the same error and none of the answers worked for me as there was no PYTHONPATH options under Window -> Preferences -> PyDev -> Python.
Instead I added PYTHONPATH setting in the menu:
Project -> PyDev-PYTHONPATH -> External Libraries -> Add Source folder
I added the path of site-packages like
/home/Documents/hcx/venv/lib/python3.5/site-packages
Now PyDev stopped complaining.

Categories

Resources