imports issues in vscode (Python) - python

I'm trying to write a python library with the following structre on vsc. When I run tests I got an error no module named pytrader. pytrader is a python package it has an init on it. In pycharm i used to set the src folder as the source directory and everything works. Any help thank you
enter image description here

The action of set the src folder as the source directory in the PyCharm is to add the src folder path to the PYTHONPATH.
In the VSCode, it has no way to add it directly, but it's possible to edit it when you debugging, you can add this in the launch.json file:
"env": {"PYTHONPATH":"${workspaceRoot}/src"},
And you can add it directly in the python file like this:
sys.path.append("D:\\TestPlace")

Related

VsCode/Python in console: file not found

In my workingdirectory I have many folders with a python script modifying data in the same folder.
When running Python in VsCode I need to give a relative path from the working directory into the folder. For example using os.getcwd(), test.py is in D:\Workingdirectory\Folder1: VsCode says, D:\Workingdirectory. Running it in console: D:\Workingdirectory\Folder1.
Direct path is not an option.
How fo i fix it?
Thanks in advance!
This is caused by vscode using workspace as root floder.
This will lead to a problem. When you use the os.getcwd() method in the deep directory of the workspace, you will still get the workspace directory.
You can open your settings and search Python > Terminal: Execute In File Dir then check it.
You can also use debug mode and add the following to your launch.json:
"cwd": "${fileDirname}"

Where is the python workspace path located in PyCharm?

I created a Python project using PyCharm (2019.3.3) in folder F:\FolderA then I realized I meant to create it in F:\FolderB. So I copied my project from FolderA to FolderB. Now when I try to install a package, PyCharm says:
Cannot start process, the working directory 'F:\Projects\FolderA\MyProject\venv\Scripts' does not exist
I come from C# background, and everything project related is saved in .csproj file. Does Python have a similar file where it writes project/workspace information? So I can point to the correct path?
Inside /venv/scripts folder there are three "Activate" files. It holds the path to the old directory.
Replace the old paths with new paths
Restart PyCharm
Install package
Here's a screenshot of the path to the files:

Adding to PYTHONPATH in VS Code

I'm trying to add the src folder to my PYTHONPATH i.E. do the same thing as Mark directory as sources root in PyCharm.
I've looked at the solutions to Visual Studio Code - How to add multiple paths to python path? but the solutions shown there do not work for me.
I've set up my minimal example as follows shown in the screenshot below:
My understanding would be that having a .env file with PYTHONPATH="./src;${PYTHONPATH}" would add the src file to the path.
Nevertheless, when running the code runner or when running python change_pyhton_path.py src is not part of the PYTHONPATH and the direct import from src fails.
I do have setting "python.envFile": "${workspaceFolder}/.env".
In pyCharm on the other hand everything works as it should after hitting Mark directory as source on src.
Thanks for helping out!
in your settings.json add:
"terminal.integrated.env.windows": {
"PYTHONPATH": "full python path here"
}
if you have problems with importing modules and you are using code-runner, try to add
"code-runner.fileDirectoryAsCwd": true
to your settings.json file
If you are trying to get auto complete working from your source directory, you could add to the PYTHONPATH environment variable as you are doing. You can also go the "vscode native" route, as there is a configuration. Open your workspace settings and add the following line:
"python.autoComplete.extraPaths": ["./src"]
NOTE: Avoid setting this at the user level as each project differs in where the source code lives
I dont know much but the json PYTHONPATH setting above looks like it would work as the json.settings file is definatly going to nead to know about your interpreter. Once you have a Python terminal prompt you have to run pythons pip file to integrate all the neccesary libraries . VS Code itself tells you to go to the command pallete and install either a venv virtual environment or create a conda (from anaconda or miniconda) set up for it. I am trying to do it myself so once I crack it I'll have more info.

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

PyCharm unresolved reference when importing class from other file

This problem has been driving me nuts. I am trying to import a class from a file in the same directory. PyCharm is giving me the "Unresolved reference" error. MyClass is defined in file.py.
I have found these questions:
Unresolved reference issue in PyCharm
Pycharm: "unresolved reference" error on the IDE when opening a working project
PyCharm shows unresolved references error for valid code
Unresolved reference when importing from sibling sub-package with
I have the following project structure:
I have marked src as the sources root...
I have set the "Add source roots to PYTHONPATH":
I have tried File -> Invalidate Caches / Restart.. (I even restarted the computer).
If I try to run it, I get the following error in the console: ImportError: cannot import name 'MyClass'
The interpreter is a virtualenv on Python 3.4 on Ubuntu x64 14.04.
If I install and import any 3rd party packages, they work fine.
If I try echo $PYTHONPATH in the terminal it returns nothing (same with env | grep PYTHONPATH. I have the appropriate virtualenv active when I try these.
Any clues?
If MyClass is defined in pack/file.py, you need to import it as:
from pack.file import MyClass
Note that using names of Python built-in types (such as file) for your own modules is a bad idea.
If you are using python version 3 try this
from .pack import myclass
This worked for me
The following steps solved my issues:
All directories required at least a blank __init__.py file
Mark all directories as source roots (per previous poster instructions)
Yes, if you are using python 3 you should add something like this:
from .pack import MyClass
It will work
I had the same issue when I tried to import a new class, however I could successfully import functions from a file in the same directory. I still dont understand why I could not import my class but thought I would share the information for other users.
#kaylebs response worked for me. However I then added the src directory to the list of source directories, first link in #lulian 's question and could remove the '.' from my file name.
There are several reasons why this could be happening. Below are several steps that fixes the majority of those cases:
.idea caching issue
Some .idea issue causing the IDE to show error while the code still runs correctly. Solution:
close the project and quick PyCharm
delete the .idea folder where the project is. note that it is a hidden folder and you might not be aware of its existence in your project directory.
start PyCharm and recreate the project
imports relative not to project folder
Relative imports while code root folder is not the same as the project folder. Solution:
Find the folder that relative imports require in the project explorer
right click and mark it as "Source Root"
Editor not marking init.py as Python
Which is the most illusive of all the cases. Here, for some reason, PyCharm considers all __init__.py files not to be python files, and thus ignores them during code analysis. To fix this:
Open PyCharm settings
Navigate to Editor -> File Types
Find Python and add __init__.py to the list of python files or find Text and delete __init__.py from the list of text files
I just delete the copied the code and delete the file and again create the same, that time it will work

Categories

Resources