VS code cannot import local python modules - python

All of my project files in VS code suddenly gives an error saying that it cannot import modules (even tho the modules are local i.e same directory and they used to work pretty well before).
The code works fine in pycharm but not in VS code, any idea whats going on?
Code:
from backend.util.crypto_hash import crypto_hash
from backend.config import MINE_RATE
error:
env DEBUGPY_LAUNCHER_PORT=34625 /home/nikhil/python-blockchain/blockchain-env/bin/python /home/nikhil/.vscode/extensions/ms-python.python-2020.3.71659/pythonFiles/lib/python/debugpy/no_wheels/debugpy/launcher /home/nikhil/python-blockchain/backend/app/__init__.py
Traceback (most recent call last):
File "/home/nikhil/python-blockchain/backend/app/__init__.py", line 2, in <module>
from backend.blockchain.blockchain import Blockchain
ModuleNotFoundError: No module named 'backend'

Close VS Code,
start it again, Go to File > open folder (open your project folder in vs code),
if it gives a prompt to select a existing virtual environment, select that.
Then you should be good to go.
More unrelated information:
I assume the issue here is that there's some problem with VS Code not recognizing the virtual environment properly. This has happened to me several times and I cannot point out why that happens. But the above solution is a quick fix and always works for me.

I'm not sure if this will resolve OP's (ten-month old) question, but I've been struggling with the same error using debugpy while trying to configure VSCode's debugger.
Step 4 of this resource resolved the issue for me. In particular, I was using the -m flag when running debugpy, but the module to be run was not in the current working directory. Once I had changed this, the debugger worked as expected. As an example, if the command was originally:
python -m debugpy --listen 0.0.0.0:5678 ./some/directory/my_script.py
then the following two commands would rectify it:
cd ./some/directory
python -m debugpy --listen 0.0.0.0:5678 ./my_script.py
After doing this, I no longer received the "No module found" error.

The main reason is that VSCode does not automatically configure environment variables for you, but PyCharm does. The simplest method is adding your module file to system path.
import sys
sys.path.append(module_file_path)
The better solution is to config your environmental path named PYTHONPATH, adding related module path to it, and after that you will no longer need import system path manually.
Hope it works!

Related

PyCharm Run Doesn't Recognize Packages But Console and Terminal Are OK

Running PyCharm 2020.1.2 Community Edition in Win10 with a Python 3.6 venv as interpreter. Installed the package feature-engine through the Project Interpret interface, installs fine and appears in the list. I can successfully import feature_engine in the PyCharm console, and I can use it fine. I can also execute a .py file with this import statement in the Terminal with the venv activated, and it also works fine. However, when I try to Run the same .py file with the import statement, I get:
ModuleNotFoundError: No module named 'feature_engine'
I have tried using import and importlib, thinking the issue was the hyphen, but those didn't work. I have tried uninstalling and reinstalling, restarting PyCharm, etc. Nothing seems to work. Any suggestions how to get the Run function working?
EDIT: Thanks for the suggestions. Attached are the Run configuration and the Project interpreter configuration. As far as I can tell, the environment is the same.
Below are examples of the error trace. The object being Run is a Flask app, which imports packages that use the feature-engine library. The actual import statement in the final import is simply import feature_engine. Trying to import the method directly using from feature_engine import variable_transformers as vt also fails.
Make sure you're using the right configuration to build your program (that is, using the python executable of the right enviroment). You can check this in the top right corner, where the run button is.

Vscode gives "ModuleNotFoundError", when running python script with right corner arrow

When debugging, this works ok, but when running without debugging, I get the error.
I tested with one line:
import fiona
Traceback (most recent call last):
File "d:\own\fionatest.py", line 1, in <module>
import fiona
ModuleNotFoundError: No module named 'fiona'
Fiona functions also work ok, when debugging, but for simplicity, I explain the situation with this one line. I can run the same script from windows command prompt normally without errors.
As explained here, debugging has specific settings on a launch file, and when in this mode the access to variables and paths might be changed as compared to the Run Python File in terminal option (which is what the arrow button does).
Therefore, I would assume that your module is not properly installed to be used in the environment you are trying to run the script. It might be helpful to know your Operational System and how someone can reproduce this behavior (as indicated in this link).
What to try
Uninstalling the module and reinstalling it, then restarting all the instances of VSCode and trying again, both the debugging and the arrow button. If the same behavior persists, probably you need to check the Python Path variables and which interpreter VSCode is using to run the Python scripts, and make sure it is the same used as reference for installing new modules.
Also, this answer might help shed a light to your situation.

'requests' imported module won't work on IDLE

(Solution given at the bottom)
I downloaded the module requests in the command prompt using 'pip install requests'. It downloads fine and works from the command prompt, but when trying to import from the IDLE PyCharm I get the error message:
Traceback (most recent call last):
File "C:/Users/asher/PycharmProjects/begginer_questions/decode_a_web_page.py", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
By copy-pasting the 'requests' file into the location:
C:/Users/asher/PycharmProjects/begginer_questions
along with the files contained in the file path:
C:/Users/asher/PycharmProjects/begginer_questions/venv/Lib/site-packages/pip-19.0.3-py3.7.egg/pip/_vendor
the code shown below finally gave no error messages.
However, this only seems like a temporary fix. Does anyone know of a permanent fix that could work or any reasons as to why this is happening? The two common problems which often cause this to occur is that multiple versions of Python are downloaded and there is already a file called requests.py, neither are the case for me. I also don't understand why I had to copy-paste the second bunch of files considering they're already contained in begginer_questions.
I'm on Windows 10 with Python 3.7.3
import requests
url = 'https://www.nytimes.com'
r = requests.get(url)
r_html = r.text
Solution:
After a long while I found the answer so for anyone struggling with this problem I hope this helps.
My confusion came from the fact that when a project is created with up to date pip and Python, a virtual environment (venv) is automatically created and is a primary place where the project will look for modules/packages. In the command prompt navigate to your project - in my case it would be:
> cd User\asher\PycharmProjects\begginer_questions
Then enter the following command the activate the virtual environment "venv" pre-made by Python or Pycharm (note this is different for Mac):
venv\Scripts\activate.bat
In this virtual environment enter the command:
pip install requests
The solution seems (and probably is) very obvious, but this should work because sys.path will always look for packages in this virtual environment instead of where ever it was installed when I tried before. Don't forget to deactivate your virtual environment in the command prompt when you're finished installing whatever packages you want by entering:
deactivate

Custom modules are not found when calling python script in console VS pycharm

I have a python3 script that I am calling in terminal; I do not use Python prefix to run it, since I did add #!/usr/local/bin/python3 in my script (I have python3 from brew, on OSX).
The interesting thing is that if I run the script in terminal, I get an import error because one of my custom module hasn't been found. If I run the same script in pycharm, it works fine.
I assume Python launch and read all the various path that I use for modules in the same way, in both pycharm and terminal, but it seems not the case. How do I set up my scripts so the modules are found, independently from their path?
I may run the same script from other machines too, so I want to be prepared and do the right thing from the start.
EDIT
I am running pycharm on OSX; Python3 is installed via Brew, but the symlink is in /usr/local/bin.
My script is running from a folder inside my home directory, so
/Users/tester/git/python_test_app/main/base/app_main.py
The custom modules are in the same folder of the main py script, but one level above: /Users/tester/git/python_test_app/main/pyutils.py
The import statement from app_main.py is
import main.pyutils as utilities
This is the stack trace that I get when running the script:
Traceback (most recent call last):
File "main/base/app_main.py", line 13, in <module>
import main.pyutils as utilities
ModuleNotFoundError: No module named 'main'
EDIT 2 and solution
Thanks to The answers, I was able to figure out that the issue is related to how Pycharm handle projects. Basically it somehow save the path where the project is; so calling an import will result in the project folder being parsed, and that's why it works fine from Pycharm.
In Python, unless PYTHONPATH has the path to my project or other modules that I wrote, it won't be able to find them, hence, raise the error.
FIX:
in my main module that I use to run the application, I did retrieve the path of the file; which I know being one level below the modules I need; so I can explicitly add the folder to the current sys.path. This will end up making possible for me to call the import successfully.
import sys
current_dir = os.path.dirname(__file__)
sys.path.insert(0, , current_dir)
The only downside is that every file and resource that I use in my project, has to be directly referred by full path; so I have to pass the current_dir around the various files in the project.
PyCharm has project interpreter settings. Verify these are the same as your system Python. Go to:
File menu
Settings
Project: <project name>
Project Interpreter
View the path to the Python executable/binary being used by the project in PyCharm and verify it matches what your system is calling (e.g., which python3)
Alternatively, it may be that you declared your sources root within PyCharm and the system cannot properly run the module as it exists in the path you're running it from (especially if inside a package). You can get around this using the -m parameter and calling it from Python.
You can also try running it from the Terminal inside PyCharm and see what it adds to the path before initializing the shell session (you can sometimes see this in your Run configurations also). If you are referring to modules not installed via pip / into the Python path but rather loaded into your project path, then this may be the culprit.
On PyCharm, next to the green "RUN" arrow press the box and then press edit configurations (see image)
There you'll have Working Directory - that path is where PyCharm is running that script from (without errors).
Try running it from the terminal within that path - that should solve your import errors.

Path import error

I'm running python 2.7 on windows. Both python27 and python27/scripts are added to the PATH, which I've verified on the command line. I used easy_install to download SOAPpy, and I have a simple python program that calls import SOAPpy at the top.
On the command line, running
python sample.py
works, as does importing in the interpreter. However running simply
sample.py
Tells me:
ImportError: No module named SOAPpy
I'm sure this is some sort of path error, but I don't understand what's going wrong. What's the difference between these two calls and how do I fix the issue? I'm sure this is a really newbie question but I'm not sure what to google. The fact that it works in the interpreter is making me scratch my head.

Categories

Resources