VSCode Unable to import 'example' pylint(import-error) - python

I am getting pylint errors in VSCode that say they are unable to import local files. However, I am able to run the files through the debugger with no problem. I thought that pylint used the same PYTHONPATH that the interpreter uses, so I don't know why this is happening.
I have my code set up like so:
dir0
-dir1
--__init__.py
--src
---__init__.py
---srcdir1
----__init__.py
----file1.py
---srcdir2
----__init__.py
----file2.py
file1.py looks like this:
def func1():
return 1
file2.py looks like this:
from srcdir1.file1 import func1
func1()
in launch.json I have:
"env": {"PYTHONPATH": "/full/path/to/dir0/dir1/src:/usr/local/bin/python"}
Pylint is giving me an import error around "from srcdir1.file1". When I go into the debugger and click run debugger, the file runs with no issues. However, if I right click and select Run Code, I get import errors that match the pylint errors.
EDIT:
I created a file in my workspace folder called .env in my workspace folder. It is as follows:
PYTHONPATH=/Library/Python/2.7/site-packages:/Users/user/path/dir0/dir1/src:/Users/user/path/client/src:/Users/user/path/product/src
Interestingly, I can import from product (the third in the list) but not from client. Is there somewhere that this environment is being overridden?
I also have the following in the file:
import os
import shutil
import sys
For some reason, import sys (but not the others) gives me the following error: unresolved import 'sys'Python(unresolved-import)

Do you have __init__.py files inside those folders? Otherwise python won't recognise them as modules and will be unable to import the code. Have a look at https://stackoverflow.com/a/448279/5015356 for more information

The problem is that you specified a PYTHONPATH for the debugger and not the general extension to send to Pylint. Try setting PYTHONPATH in a .env environment variable definition file.

Related

Getting a ModuleNotFoundError when trying to import from a particular module

The directory I have looks like this:
repository
/src
/main.py
/a.py
/b.py
/c.py
I run my program via python ./main.py and within main.py there's an important statement from a import some_func. I'm getting a ModuleNotFoundError: No module named 'a' every time I run the program.
I've tried running the Python shell and running the commands import b or import c and those work without any errors. There's nothing particularly special about a either, it just contains a few functions.
What's the problem and how can I fix this issue?
repository/
__init__.py
/src
__init__.py
main.py
a.py
b.py
c.py
In the __init__.py in repository, add the following line:
from . import repository
In the __init__.py in src, add the following line:
from . import main
from . import a
from . import b
from . import c
Now from src.a import your_func is going to work on main.py
Maybe you could try using a relative import, which allows you to import modules from other directories relative to the location of the current file.
Note that you will need to add a dot (.) before the module name when using a relative import, this indicates that the module is in the same directory as the current file:
from . import a
Or try running it from a different directory and appending the /src path like this:
import sys
sys.path.append('/src')
You could also try using the PYTHONPATH (environment variable) to add a directory to the search path:
Open your terminal and navigate to the directory containing the main.py file (/src).
Set the PYTHONPATH environment variable to include the current directory, by running the following command
export PYTHONPATH=$PYTHONPATH:$(pwd)
At last you could try to use the -m flag inside your command, so that Python knows to look for the a module inside the /src directory:
python -m src.main
I've had similar problems in the past. Imports in Python depend on a lot of things like how you run your program, as a script or as a module and what is your current working directory.
Thus I've created a new import library: ultraimport It gives the programmer more control over imports and lets you do file system based, relative imports.
Your main.py could look like this:
import ultraimport
a = ultraimport('__dir__/a.py')
This will always work, no matter how you run your code, no matter what is your sys.path and also no init files are necessary.

VSCode Python error in importing modules from subdirectories

My project file structure is like this,
project/src/test/myscript.py
project/src/utils/file_utils.py
When I run myscript.py, which has from utils import file_utils, it gave me error:
ModuleNotFoundError: No module named 'utils'
Previously in Pycharm IDE I did not get this type of error (maybe due to _ init _.py), the subdirs of the same parent dir could be detected. But not sure for VSCode, is there something I need to add for specifying the file structure? And I opened the folder project as my VSCode workspace (not sure if where I open the workspace matters)
I tried adding:
in the /project/.vscode/launch.json
"cwd": "${workspaceFolder}/src"
or in the begining of myscript.py
import sys
import os
src_path = os.path.dirname(os.path.abspath('/project/src/'))
sys.path.insert(0, src_path)
But none of them works. Does anyone have any insights? Thank you very much!
You could consider placing a .env file at the root of your project which adds your source directory to PYTHONPATH. i.e. something like
>>> cat /project/.env
PYTHONPATH=/project/src/
>>>
Your code will look a smidgen nicer without the explicit manipulation of sys.path.
VSCode's usage of .env files is documented here.
Yes, in Pycharm you didn't get this error because it adds __init__.py file automatically when you create a python module. The python identifies the structure of your project through these files, if your folder does not have __init__.py python will understand it as just any folder.
Unlike pycharm, vscode uses the workspace as the root directory to retrieve files. The first method you try is to write it in the launch.json file, which is applicable to debug rather than running it directly. You can use the following code to import:
from src.utils import file_utils

Visual Studio Code tells me it can't import python module, yet it runs the code

I am running a script in many folders and subfolders, the structure is kinda confusing but it basically is like:
src/
controllers/
__init__.py
a.py
b.py
models/
__init__.py
c.py
__init__.py
main.py
The ^^^ is supposed to be the red error underline, main.py looks something like:
from controllers import a
^^^^
import models.c
^^^^^^
a.py:
import models.c
^^^^^^
I tried both, from and regular import, because maybe only one is bugged, but no, in VSC at every place I import like this, it tells me unable to import [directory] (it still runs from VSC and from the terminal via python3 main.py)
Things I tried
Restarting VSC
Rebooting my PC
Changing stuff in __init_.py (yet nothing systematic, just playing around)
Is this a visual studio code issue, is it bad importing? Should I put stuff into __init__.py? Can I supress this issue or fix it somehow else?
When importing modules in other folders, VSCode searches for files from the parent folder of the currently running file by default. For example: "import models.c" in "a.py", the parent folder "controllers/" of "a.py" does not have "models", so the terminal displays a warning.
When I removed the same level file "__init__.py" of "main.py", the terminal did not display errors and warnings:
For "a.py", I added the following settings in "launch.json", which adds the project folder path to the system path for VSCode to find:
"env": {
"PYTHONPATH": "${workspaceFolder}"
}
Debug a.py:
Update:
On the premise that the code can run, I use the following settings to turn off the "import-error" displayed by Pylint:
"python.linting.pylintArgs": ["--disable=E0401"],

Make a class from one project visible in other project (Python,Pycharm)

I created in PyCharm a Class in Project1, called Class1. Now I have created Project2 (no matter in which directory). I want Class1 to be imported in this project (Project2) as well (like all other modules, like os, requests, numpy). Could you please advice how I can do it?
I have tried:
- from Class1.py import Class1
- marked as source code directory of Project1
Still when writing in window of Project2 "from Class1.py import Class1" interpreter does not recognize it
Finding code to import python interpreter looks at sys.path.
https://leemendelowitz.github.io/blog/how-does-python-find-packages.html
So that you should add some lines of code
import sys
sys.path.append('path to project1')
Or use PYTHONPATH environment variable.
One way to do that is to modify PYTHONPATH (import path). Import path is a list that will be checked by the third default finder during importation process.
The first finder will locate built-in modules and the second frozen modules.
Read this for more information : https://docs.python.org/3.7/reference/import.html
If your class1.py is in "/home/project1"
you can do in terminal :
export PYTHONPATH=$PYTHONPATH:/home/project1
or directly in python terminal :
import sys
sys.path.insert(0,"/home/project1")

Python "module not found" error when importing from folder?

I have the common problem of the "module not found" error when trying to import a file within a folder in my project directory as a package. I've tried several solutions from Stackoverflow answers, but none are working for me. Here's what's going on, and what I've tried:
I'm working in a conda environment devenv on a Flask project, using PyCharm, and have a project directory like this:
/some/path/project_root/
migrations/
static/
templates/
reporting/
__init__.py
code.py
tests.py
Inside the tests.py file there are import statements to import code.py as a module:
from .code import my_function
However, when I run (devenv) me#comp:project_root$ > python reporting/tests.py
I get the error: ModuleNotFoundError: No module named '__main__.code'; '__main__' is not a package
I tried appending the project directory path to $PYTHONPATH, and echo $PYTHONPATH returns /some/path/project_root/
What do I need to configure to get this to work properly? Also, whatever settings I need to change, can I make those settings specific to the development environment I'm using?
Change from .code import my_function to from code import my_function. The top level of a package is defined by the highest folder with an __init__.py file. So the top level of your project is the reporting folder and code.py does not need to be a relative import. Best to either avoid relative imports or get an editor like PyCharm that will take care of it for you!

Categories

Resources