I'm trying to configure Sumblime CodeIntel so that it works with django. The official docs state that:
For adding additional library paths (django for example), either add those paths as folders to your project, or create
an optional codeintel configuration file in your home or in your
project's root.
Configuration files (~/.codeintel/config or
project_root/.codeintel/config). All configurations are optional.
I localized and edited the ~/.codeintel/config file, so that config now looks like this(added the bolded part):
{
"Python": {
**"python": "C:/Python27/django-tom/Lib/site-packages",**
"pythonExtraPaths": [
"libs",
"~/Applications/Sublime Text 2.app/Contents/MacOS",
"/Applications/Sublime Text 2.app/Contents/MacOS",
]
}
}
`django-tom is my virtualenv django folder. However the autocompletion is not working for django (but works fine with the rest of python).
this is how i have it
{
"Python": {
"python": 'path to python/bin/python',
"pythonExtraPaths": ['path to pytho/python2.7/site-packages/',
]
},
}
if you're using env you can have hooks with virtualenvwrapper
let me know if you need help on setting that up
also there a sublimeRope package which is python specific
Related
I am following AWS User Guide to create a Python package from TypeScript Source via JSII. My TypeScript source looks like this:
export interface GreeterProps {
readonly greetee: string;
}
export class Greeter {
private readonly greetee: string;
public constructor(props: GreeterProps) {
this.greetee = props.greetee;
}
public greet(): string {
return `Hello, ${this.greetee}!`
}
}
This is section from JSII config for Python:
"targets": {
"python": {
"distName": "jsii-test.jsii-test",
"module": "jsii_test.jsii_test"
}
}
The project builds without errors and, and Python package is created successfully. I uploaded the package (via twine) to AWS CodeArtifact, and installed (via pip). When I import it in interactive Python console (import jsii_test) it imports successfully, but it doesn't seem to have the members exported from the original TypeScript source (GreeterProps, Greeter). What am I missing?
Project source: https://github.com/YuriGal/jsii-test
Turned out pip was installing package into incorrect location (I have to sort out my python versions). When I added path where the package was installed
import sys
sys.path.append('/usr/local/lib/python3.10/site-packages')
everything worked.
I have a folder with a few subfolders as here:
my-project/
input/
data.csv
src/
script.py
I want to read data from my-project/input/data.csv within script.py, so I have:
import pandas as pd
data = pd.read_csv('../input/data.csv')
However, my workspace is my-project so when I run script.py it returns:
Exception has occurred: FileNotFoundError [Errno 2] No such file or
directory: '../input/data.csv
which is understandable as input is within my-project, not at the same level. However, referring with .. really feels like the correct way to refer to data.csv as we do it from script.py. But maybe I'm wrong?
In case this is a reasonable way to refer to my data file - how can I setup the VSCode to be able to run the script without returning the error? I think there should be a way to add the subfolder to searching path, without needing to open the subfolder as a workspace, but I had a bad luck trying to find it.
#Edit: Please note that I'm aware of the concept of relative/absolute paths. This questions is more about VSCode settings. I am also willing to accept the answer: "No, referring with ../input/data.csv is the dumb thing to do in this settings. You should refer with input/data.csv instead, because..." (it's contradictory with my current understanding, but I could be entirely wrong and I'd be happy to learn a different point of view)
I believe this is simpler than you thought, let do it together!
The used extensions ...
I believe the below steps are not so hard!
Switch the default interpreter to the created virtual environment
Create a simple launch.json, with simple choice python script
Guess what now! All we have to do now is select a script.py file in the editor then ....... RUN!
You can see the result in the terminal.
let's talk a bit...
The generated launch.json file will force us to select the **src.script.py" in the editor before we click the start button every time we want to launch the program, if you like so, I can suggest a more proper way
In step 6, you can choose Module instead of Python file, after that the editor will prompt you a field asking for the module name, our input must be src.script.
We will get our launch.json file like this ...
And now, we can start the program from where we want, which means if the opened file in the editor is "src/data.json" as an example,
going to the debugger section and click start will always start the src/script.py file.
If you run the script in your workspace then input/data.csv should work.
The location is not based on where your script is, but from where you run it.
To get the current working directory you can use
import os
print(os.getcwd())
and then go from there.
Edit: you can change the working directory in your launch.json as described here: https://stackoverflow.com/a/55072246/14246131
by setting launch.json
"cwd":"${fileDirname}"
// or use "cwd":"${workspaceFolder}/src" to specifically assign /src as your current working directory
then all the relative path starts from the py file you are running (in your case will be my-project/src), you should be able to use:
data = pd.read_csv('../input/data.csv')
the launch.json variables can be referenced here: https://code.visualstudio.com/docs/editor/variables-reference
here's my sample env for your reference:
file structure:
my-project/
.vscode/
launch.json
input/
xxxxx.txt
src/
main.py
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd":"${fileDirname}"
}
]
}
main.py:
with open('../input/xxxxx.txt', 'r') as file_input:
res = file_input.read()
print(res)
I would typically do the following -- figure out the directory where my current .py file is and use a relative path from there
import os
py_folder = os.path.dirname(os.path.abspath(__file__))
input_folder = os.path.join(py_folder, '../input')
data = pd.read_csv(os.path.join(input_folder', 'data.csv'))
this way it does not matter from which directory you run your .py, and it works for any development environment ie not VSCode specific
You are probably referring to the file like ../input/data.csv in relation to the path of your script.py
But that is not the correct way to go about it you should be adding the file path in relation to from where you are executing the script.py, which I assume is from the root of project folder most probably. Especially if you are using the run python command from VS code.
Hence why the path input/data.csv should work in that case.
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.
$ where python
C:\Users\Idan\AppData\Local\Programs\Python\Python38\python.exe
C:\Users\Idan\AppData\Local\Microsoft\WindowsApps\python.exe
The Error:
Idan#DESKTOP-A16D3QA MINGW64 ~/Desktop/ttt
$ C:\Users\Idan\AppData\Local\Programs\Python\Python38\python.exe -u "c:\Users\Idan\AppData\Local\Programs\Python\Python38\s.py"
bash: C:UsersIdanAppDataLocalProgramsPythonPython38python.exe: command not found
deafault settings json file:
// Path to the pipenv executable to use for activation.
"python.pipenvPath": "pipenv",
// Path to the poetry executable.
"python.poetryPath": "poetry",
// Path to Python, you can use a custom version of Python by modifying this setting to include the full path.
"python.pythonPath": "python",
settings.json
What I tried to do (integrate pipenv instead of venv):
"python.pythonPath": "C:\\Users\\Idan\\AppData\\Local\\Programs\\Python\\Python38\\python.exe",
"python.pipenvPath": "pipenv",
"python.testing.pytestEnabled": true,
"python.venvPath": "C:\\Users\\Idan\\.virtualenvs",
],
"code-runner.executorMap": {
"python": "$pythonPath -u $fullFileName"
},
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
other configuration I tried resulting in same error:
"python.venvPath": "C:\\Users\\Idan\\.virtualenvs",
// this is the actual locatation
// of the pythonpath C:\\Users\\Idan\\.virtualenvs\\Idan-iyfIpKqV\Scripts\python.exe
"python.pythonPath": "$venvPath\\pipenvPath\\Scripts\\python.exe",
//"python.pythonPath": "$venvPath\\ENV-NAME\\Scripts\\python.exe",
This is the full settings.json I have:
https://gist.github.com/IdanBanani/0d562770f14f3098debb6e1d47179e3f
previously, combining lines from these two sources was working (venv):
https://github.com/CoreyMSchafer/dotfiles/blob/master/settings/VSCode-Settings.json
https://github.com/xames3/xai_django/blob/bcaf169837d484d0bcf8686c18dc0529d1469034/.vscode/settings.json
but I tried to replace to pipenv, and might try in the future to automatically set it to create and activate the virtualenv
(pipenv install, pipenv shell) but not sure how easy it is
Also: I had to remove these lines of the thefuck project from .bashrc file because of error messages in the output console(maybe the installation/pip package got removed)
eval $(thefuck --alias)
# You can use whatever you want as an alias, like for Mondays:
eval $(thefuck --alias FUCK)
This is my current fix, but I don't think it's good enough for the generic case
Why does it keep creating the virtual env in a constant folder name Idan-iyfIpKqV?
"python.venvPath": "C:/Users/Idan/.virtualenvs",
"python.pythonPath": "C:/Users/Idan/.virtualenvs/Idan-iyfIpKqV/Scripts/python.exe",
I'm trying to get autocompletion working in Sublime Text 3 via the Anaconda plug-in. So far I've been successful getting autocompletion working with the standard python libraries but not for Django.
My sublime project file looks like this:
{
"folders": [
{
"follow_symlinks": true,
"path": "."
}
],
"settings": {
"python_interpreter": "/Users/user/.virtualenvs/project/bin/python",
"suppress_word_completions": true,
"extra_paths":
[
"/Users/user/.virtualenvs/project/lib/python2.7/site-packages"
],
"anaconda_debug": true,
},
"build_systems":
[
{
"name":"Virtualenv 2.7 Project",
"shell_cmd": "/Users/user/.virtualenvs/project/bin/python -u \"$file\"",
"path": "/Users/jamiehush/.virtualenvs/project/bin",
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
]
}
I'm also running "subl" from a terminal while inside a virtual environment.
You shouldn't need any special extra_path to make autocompleting work with Django. Nothing make Django special, anaconda should be able to autocomplete whatever is visible by your configured python interpreter.
Make sure that the virtual environment in project has a copy of Django installed on it. If you have virtualenwrapper installed should be as easy as:
$ workon project
$ python
import django
If you have Django in your virtualenv, is possible that the anaconda JsonServer was started before you installed the library and it's not able to see it. Restart your Sublime Text 3 and try again.
In case that you still have problems, send an email to the anaconda's mailing list or open an issue in the Github project (https://github.com/DamnWidget/anaconda/issues) indicating your operating system, ST3 build and Python version that you are using so we can help you further.