vscode do not find my custom python package - python

I'm new to VS Code for python development on Windows and my pylint cannot find a package.
This is my project directory structure.
workspace/ <- This is VS Code workspace (E:\workspace)
.vscode/
launch.json
settings.json
project1/
mypackge/
__init__.py <- In here, I wrote: `import mypackage.first_sub_pkg`
first_sub_pkg/
__init__.py <- In here, I wrote: `from .second_sub_pkg.mymodule import MyClass`
second_sub_pkg/
__init__.py <- In here, I wrote: `from .mymodule import MyClass`
mymodule.py <- This module has class: `MyClass`
test_script/
mytest.py
project2/
etc.../
And I wrote the mytest.py script code like:
from mypackge.first_sub_package import MyClass
I'm using C:/Anaconda3/python.exe for python interpreter
When I click the button on the upper side ▷ (Run Python File in Terminal) on the upper right side of VS Code, I get this error message
PS E:\workspace> & c:/Anaconda3/python.exe e:/workspace/project1/test_script/mytest.py
Traceback (most recent call last):
File "e:/workspace/project1/test_script/mytest.py", line 1, in <module>
from first_sub_pkg.second_sub_pkg import MyClass
ModuleNotFoundError: No module named 'first_sub_pkg'
Also, I added workspace/.vscode/launch.json like:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"pythonPath": "${command:python.interpreterPath}",
"env": {
"PYTHONPATH": "${workspaceFolder};E:/workspace/project1"
}
}
]
}
And workspace/.vscode/settings.json like:
{
"python.autoComplete.extraPaths": [
"E:/workspace",
"E:/workspace/project1",
"E:/workspace/project1/first_sub_pkg",
],
"python.pythonPath": "c:/Anaconda3/python.exe",
"terminal.integrated.shell.windows": "C:/windows/System32/WindowsPowerShell/v1.0/powershell.exe",
"python.linter": "pyLint",
"python.linting.pylintPath": "pylint"
}
And my user settings.json file is like:
{
"python.autoComplete.extraPaths": [
"E:/workspace",
"E:/workspace/project1",
"E:/workspace/project1/first_sub_pkg",
]
}
I already ran this test script in Eclipse + pydev environment, and there was no problem running it.
But somehow VSC cannot import my modules.
I seems like system path problem since it works well when I run python and append 'E:/workspace/project1' to system path (import sys; sys.path.append('E:/workspace/project1');), but I cannot find out how to solve the problem. (Adding system variables in Windows settings did not worked neither).
What did I miss? Somebody please help me. I searched for 2 days but got nowhere.

first_sub_pkg is not in the same directory as the mytest.py file. You first have to move up one level to project1/ then into mypackage/ then continue with the rest of imports. So the imports you do in mytest.py should be like so:
from ..mypakage.first_sub_pkg.second_sub_pkg.third_sub_pkg.mymodule import MyClass
Why you have so many sub directories I don't know, but your directory structure will get really confusing really fast.
Keep the zen of python in mind when coding.

Solutions:
One:
change this statement :"from first_sub_pkg.second_sub_pkg import MyClass" in mytest.py
to "from mypackage.first_sub_pkg.second_sub_pkg.third_sub_pkg.mymodule import MyClass".
Two:
change 'env' in lanuch.json from "PYTHONPATH": "${workspaceFolder};E:/workspace/project1"
to "PYTHONPATH": "${workspaceFolder};${workspaceFolder}/project1/mypackge".
Explain:
The Python only can search the paths in PYTHONPATH. If the module nested in the paths you need to use '.' to connect the folder until points to the module file.

This sulotion is not for mac.
Open vs code press ctrl+shift+p
Enter: Python:Select Interpreter
Choose your environment and run the code again. (rjz is my environment name)
If this doesn't fix, you need to use CMD for install packages with conda or pip. In my case install packages with VS code terminal doesn't fix the problem.
For some packages, you need to install with vs code terminal expect CMD.

Related

Debugging Python Module from within Github Repo in VSCode

I have a python library in github I want to debug. The library has setup.py as well as a pip released package. So I can install this module using either pip install git-sim or python3 setup.py install.
This module adds a command to the path and I can execute in terminal with git-sim .
Main Problem: I want to clone the github repo and open vscode inside the cloned repo and debug the code getting executed while I am running the command from the terminal. The breakpoints should hit the file inside the repo.
Link to the github Repo: https://github.com/initialcommit-com/git-sim
I went searching with these requirements. Best I could come up so far is
An edit mode in setup.py which can be started by pip install -e . . While I ran this command and was successful I did not see a way to debug it.
How do we debug a module in Vscode? Give this code in launch.json
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "git-sim",
"justMyCode": false,
}
But while I am running this I am getting an error, no module named git-sim even though the same command works outside the debugger in the terminal. i.e both git-sim and python3 -m git_sim
Any suggestion of where I maybe going wrong? Or if there is some alternative option I have not considered
Found the issue. I made a mistake in assuming the terminal command git-sim and the actual python -m git_sim were same.
Module Name and Terminal commands are different. So if we modify launch config from "module":"git-sim" to "module":"git_sim" it works. Modified config given below:
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "git_sim",
"justMyCode": false,
}

How do I set up VS Code for Python to correctly launch/debug individual files such that relative imports are respected?

I found this answer very useful to understand relative imports in Python. However I have found difficulty in getting VS Code's "Current File" to play nicely with this, since it launches the file directly using ${file}.
To summarise said answer, suppose we have a structure like this:
mymod/
__init__.py
apple.py
orange.py
If orange.py imports something from apple.py:
from .apple import apple_function
then the correct way to run orange.py as a script without an ImportError is with the following command from the directory containing mymod:
python -m mymod.orange
Currently, I manually enter a command similar to the above into the terminal, which works, but I'd prefer to use a keyboard shortcut that works regardless of filename and saves me some typing.
Is there anything I can add to the launch.json to have a configuration that launches python for each particular file as above automatically?
Use the command extension.commandvariable.file.relativeDirDots from the extension Command Variable
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"console": "integratedTerminal",
"module": "${command:extension.commandvariable.file.relativeDirDots}.${fileBasenameNoExtension}",
}
]
}

How to run python from different drive using Visual Studio Code

My OS is Windows 10.
I have test.py file in E drive.
I installed Python 3.7.2 and Visual Studio Code in C drive.
I set system path for Python 3.7.2 so I could run python on CMD on both of the drives.
I also set python.pythonPath in setting.json file in .vscode under my work folder.
So python.pythonPath is same as the system path.
but I can't run that test.py file on VScode.
It shows python 3.7.2 file's path and says "No such file or directory".
Is there a way to run python file on different drive using VScode?
You can use debugging to run specific files in a reusable way.
https://code.visualstudio.com/docs/python/debugging
It will create a launch.json file with contents similar to this. You can add additional
properties. VSCode is good about helping you create and edit the launch.json file.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "RunPython",
"type": "python",
"request": "launch",
// run a file by specifying a full path
"program": "E:/FullPathTo/FileA.py",
// OR run the file currently open in VSCode
// // "program": "${file}",
// OR run a file relative to the current folder you have open
// // "program": "${workspaceFolder}/folder/FileB.py"
"console": "integratedTerminal",
"args": ['InputArg1','InputArg2']
}
]
}
If you've already set Python as an environment variable, you can simply route to the directory where the file is present (in this case E: drive) and run the command:
python test.py
I installed Code Runner Extension and it followed my system path of python 3.7.2 automatically.
Now I can simply run my code with this short cut "Crtl+Alt+N" instead of entering "python test.py" every time on the terminal.

VScode debugger cannot import modules from site-packages

I have C:\Users\user\AppData\Roaming\Python\Python37\site-packages directory in sys.path
And while I run code via cmd it works fine.
However, when i try run it via vscode debugger, I get this:
No module named request
So, how can I fix this?
According to your description, it is recommended that you could try the following methods:
Check the python interpreter for the current VSCode.
When running python files in the cmd window, the system uses the python set by the environment variable.
About it can run in cmd, but not in VSCode.This will happen if the Python interpreter used in VSCode is different from the cmd. Reference:python-interpreter.
Try using pip to install the required module again. Use 'pip --version'(Linux and Mac:'pip -v') at the terminal to check whether the version of pip comes from the current interpreter.Use 'pip install <modules name>' to install it. Then, check whether the module is in the list by 'pip list'.
Attempt to reload VSCode.
Above, I could import the required modules from similar locations. My environment:python:3.8.3; VSCode:1.47.2; Win10.
Update:
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}

How to run python in Visual Studio Code as a main module

How to run python in Visual Studio Code as a main module?
From the command line I would use the -m switch, like
python -m program.py
I need this to make relative imports work.
Is there something I could add to the launch.json file?
If this isn't possible, I maybe need to do something with runpy see python docs, but it would be nice if vscode can do this.
Edit:
For the moment I use, as a workaround, an extra run.py file which I place outside the package I want to run. Then configure vscode to run that file:
"program": "${workspaceRoot}/../run.py"
From run.py I import the package and call its entry-point function.
The documentation for debugging a module can be found here: https://code.visualstudio.com/docs/python/debugging#_debugging-specific-app-types
All you need to do is:
Select the Python: Module debug cofiguration in VS Code
Edit the launch.json and locate the Python: Module config section and replace the value for the setting module with the module name, e.g. program
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: app",
"type": "python",
"request": "launch",
"module": "module_name.app",
"console": "integratedTerminal"
}
]
}

Categories