Visual Studio Code Project Importing from Wrong Directory - python

I have the below directory structure. In my test2.py file, I am importing resource.py. It is however referencing resource.py from Folder1 instead of Folder2. Can someone explain to me what is happening, and/or how I can import from the correct directory?
-Folder1 (Original folder)
--resource.py
--Folder
---test1.py
-Folder2 (Copied from folder 1)
--resource.py (modified global variable values)
--Folder
---test2.py
Update: I was able to workaround my problem by adding the below snippet of code. Any additional suggestions are welcome, so I don't need to apply this code to each .py file in Folder2 that needs resource.py
import sys
sys.path.remove('path\\to\\not\\wanted\\directory')
sys.path.add('path\\to\\wanted\\import\\source')

After Python: Clear Internal Extension Cache from Command Palette, specify the clear path about importing the module with the following code:
import sys
sys.path.append("./")
import folder2.resource as f2r
See result:

Related

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

relative reference in python

am beginner in python and working on multi folder structure and struggling to refer the files using relative path. tried in different ways to refer the files in other folders but ended up in error "attempted relative import with no known parent package". Can somebody explain how the relative paths will work in python?
here is the example what am trying to achieve..
folder structure
Main
source
Function1
inputs
1.py
2.py
uts
test_1.py
code_1.py
code_2.py
Now inside test_1.py am trying to refer code_1 using relative path like
from ..code_1 import Code
from .code_1 import Code
but, ended up in error..
some where I found that we need to have init.py in each folder to use relative path and I created empty init.py in each folder but, no use..
I may get the answer but more importantly need to know how this relative path works in python.
Thanks in advance
I've also had issues with relative imports in Python and thus I've created an experimental, new import library: ultraimport
It gives you more control over your imports and lets you do file system based imports.
You could then write in your test_1.py:
import ultraimport
Code = ultraimport('__dir__/code_1.py', 'Code')
This would import code_1.py from the same directory as test_1.py.
This will always work, no matter how you run your code.

ImportError: attempted relative import with no known parent package STILL NO SOLUTION

I have looked at I think 5 different answers to this problem, yet none of them have worked for me yet. For reference, I've looked through all of these posts:
Relative imports for the billionth time
Attempted relative import with no known parent package
"Attempted relative import with no known parent package"
From what I've gathered, there are two solutions to this problem:
Move the .py file you're trying to import functions from into the same directory as the script you're trying to run (this works, but it is not a good solution, I should be able to import from a parent directory without this error)
Create a __init__.py file in the directory of the .py file you're trying to import from, and use import package_name to it. (I have tried this, but same issue)
Here is my project's structure:
I'm trying to run the test.py script, which (attempts) to import the function add_technical_indicators from the add_technical_indicators.py file. My import statement looks like this:
from ..utils.add_technical_indicators import add_technical_indicators
Looking at the folder structure again, I have to go UP one directory, then into the utils folder to bring in the add_technical_indicators .py file, and finally the function add_technical_indicators.
Here's what I have tried so far:
from ..utils.add_technical_indicators import add_technical_indicators
from .utils.add_technical_indicators import add_technical_indicators
from utils.add_technical_indicators import add_technical_indicators (this doesn't work of course because add_technical_indicators is not in the same folder as the script being run)
Created an __init__.py file in the utils folder that reads import add_technical_indicators
Created an __init__.py file in the misc folder that reads import test
None of it works. I need a concise and actionable answer as to why this is still not working. I'm running Python 3.7.9, Windows 10, and VS code in case that matters.
I have looked through previous, repeat answers but none of them have worked for me, so although this IS a duplicate question, please do not close it until I have a solution because linking to the already "answered" questions didn't help me.
short solution
In test.py import as from utils.add_technical_indicators import add_technical_indicators
and run as python -m misc.test (not test.py) in parent directory(in STOCK_PEAKS_ADN_THROUGHS_2)
explained
python cannot import files from upper directory of your working directory unless you add them to PATH, so from ..utils.add_technical_indicators import add_technical_indicators won't work.
python finds files starting from your working directory, so from utils.add_technical_indicators import add_technical_indicators in test.py can find utils/add_technical_indicators.py if you run script at parent directory.
python -m misc.test will run misc/test.py in parent directory. Note that python misc/test.py will run script in misc directory and will give you same error.
You did the right thing here: from ..utils.add_technical_indicators import add_technical_indicators
The main issue must be in the imports of utils/add_technical_indicators.py file
Did you try importing stuffs inside add_technical_indicators.py relative to itself (if so, those imports only work when add_technical_indicators.py is run instead of test.py)
In contrast to what minolee has said Python actually can import files from upper directories. Python has a built-in SourceFileLoader that can load Python code from any file in the file system, also from any upper directory of your working directory.
It requires some boilerplate code, so I have decided to wrap this approach into an experimental import library: ultraimport
ultraimport can do file system based imports. In your test.py you could then write:
import ultraimport
add_technical_indicators = ultraimport('__dir__/../utils/add_technical_indicators.py')
This will always work, no matter what is your current working directory and no matter what is your current sys.path. You don't need to create __init__.py files and it also works if you run the code as a script or as a module.
One caveat when importing files like this is if the imported code contains further relative imports. ultraimport has a built-in preprocessor to automatically rewrite subsequent relative imports so they continue to work.

How to INCLUDE code located in another folder?

I have a piece of code located in a file (utils.py) in a folder different from the one my current script is located in. I tried:
from "/Z/scripts/utils.py" import *
but it gives a syntax error. Is there a way to "include" my own code located elsewhere other than the current folder?
You need to add that directory to your python path
import sys
sys.path.append("/Z/")
from scripts.utils import *
Make sure the scripts directory contains an __init__.py file
You can import code that is in a directory if it is added to PYTHONPATH. See here for more details.

Importing error in python using eclipse

I have two files one is:
file1.py that is located at myapp/file1.py
file2.py at test/file2.py
I want to use the function of file2.py in file1.py
How can i import file2.py to file1.py?
I tried to: from test.file2 import file2 it compiles but when i run it i got an error from the debug: Import Error no module named file2
What is the right way to do this?
By Default, Python searches in the project directory and hence the files from other directories cannot be imported as we do for the files available locally in the project folder.
But to accomplish that we might want to amend the system path which can be done in the following way.
import sys
sys.path.insert(1, '/path/to/your/filefolder/')
#also sys.path.append(0,/'path/to/your/filefolder/[file])
import [your file]
Hope this can help :)

Categories

Resources