How to INCLUDE code located in another folder? - python

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.

Related

ModuleNotFound error only in Flask subfolders, not in root

I am having a very annoying problem with module imports within a Flask app.
This is my file structure:
root > app > views > tests
In the views folder, there is a file called data.py. I wish to import this into a file called test_data.py in tests:
from app.views import data
This gives a ModuleNotFound error, saying that app is not a module (I have added an __init__.py file, although I believe this is no longer needed in Python 3).
However, in the root (foo) folder, I have another file that is using exactly the same absolute import successfully:
from app.views import data
Can anybody help me out, please, with how I am able to import successfully into files other than the root folder?
So, if your test_data.py is inside tests, and you wish to import data.py from views folder, you need to tell python to look into the folder specifically. You can do this in your test_data.py using this:
import sys
sys.path.insert(1, '/root/app/views')
import data
remember that the path is the absolute path. If you are on windows, this would start from C:/ or something and on linux from root. Do not use the relative path but only absolute.
Hope this helps!

Visual Studio Code Project Importing from Wrong Directory

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:

Import classes/functions from Python files saved in same folder showing "No Module Named" error

As per screen print, import shows error in Python 3.7 version, earlier it was working fine in version Python 2.7 and I am using IntelliJ Idea.
If you see, EOC related .py files are in the same folder and have classes which are being called in Main_EOC.py by passing objects which are inter-related. It's amazing to see the red line while importing files from same folder.
Please help me why it's showing such error
"This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.`"
Also, if you see the line which have full path, is not showing error
from EOC_Module.eoc.script.config import Config
Please help me if there is a way to add this full path on top of the code or other option.
The behavior of import path search changed between python2 and python3. The import path always includes the directory from which the main module was loaded, but it no longer includes directories from which modules were imported.
You need to change your import statement syntax as follows, if you want to import a module that lives in the same directory as the module in which you do the import:
# old way, import works if the named module is in this module's directory
import x
# new (Python3) way:
from . import x
For the second part: adding a path so all code can import from a certain directory: if that directory is (and will always be) relative to your main: you can add a few lines in the main module to make it available. Something like this:
import sys # if you haven't imported it already
import os.path
home = os.path.dirname(sys.argv[0])
sys.path.append( os.path.join(home, "EOC_Module/eoc/script") )
# now, you can import straight from the script directory
import EOC_Intraction
When using pycharm the root directory for your python executable is the same as the root directory of your project, this means that python will start looking for files in the root directory with this files:
.idea/
EOC_module/
logs/
reports/
sql/
This is the reason of why: from EOC_Module.eoc.script.config import Config works.
If you execute your code from the terminal with: python3 Main_EOC.py (not pycharm) the root directory for your python will be the same as the one containing the file, all the other imports will work but from EOC_Module.eoc.script.config import Config not.
So you need to make your imports from project directory if you are using pycharm.

Appending network pc to sys.path

Is it possible to add network pc to sys.path? Currently I'm only able to append a shared folder. When I try to import a script inside this folder I get ImportError. I have the init file in there. As I know this might be because sys.path doesn't actually see the appended folder itself but the files, folders inside?
Because import works from a folder inside the first folder.
directory structure:
//PC023/SharedFolder/folder
so i'm soing this:
sys.path.append(os.path.normpath("//PC023/SharedFolder"))
then I try to import:
from SharedFolder import script -> I get ImportError saying no module exists with this name.
if I do from folder import script2 -> it works
My question is what is the real reason the import doesn't work and can I append the directory like this:
sys.path.append(os.path.normpath("//PC023")) - > because it doesn't seem to work this way

relative path not working even with __init__.py

I know that there are plenty of similar questions on stack overflow. But the common answer doesn't seem to be working for me.
I have a file structure like this
proj/
lib/
__init__.py
aa.py
bb.py
test/
__init__.py
aa_test.py
I figured that if I include the code in my test.py
import lib.aa
or
from lib import aa
I would be able to reference the modules in the lib/ directory. But that did not work.
So I tried to add to path, and it adds it correctly:
os.environ["PATH"] += ":%s" % os.path.abspath(os.path.join("..",""))
print os.environ["PATH"]
but even now when I try the import statements above... I keep getting the error
ImportError: No module named aa
or
ImportError: Importing from non-package <Something...>
Is there something obvious I am missing?
Is there a way to check if I have configured my __init__.py files correctly, or to see my package hierarchy?
You need to update your sys.path, which is where python looks for modules, as opposed to your system's path in the current environment, which is what os.environ["PATH"] is referring to.
Example:
import os, sys
sys.path.insert(0, os.path.abspath(".."))
import aa
After doing this, you can use your functions in aa like this: aa.myfunc()
There's some more information in the accepted answer for python: import a module from a directory
The lib directory needs to be in your python module search path, which isn't the same things as the search path used by your shell.
This will probably work for you:
import sys, os
sys.path.append(os.path.abspath(".."))
However, it is probably better to run your code from a context where the lib package is already on the path. Such as from the 'proj' directory.
Where is the code that you're trying to import lib.aa from? I'm guessing /proj/ is not your working directory and it would need to be as it's setup right now. Instead of PATH, you would want to add your directory to PYTHONPATH so it appears in the search path for an import. See http://docs.python.org/tutorial/modules.html#the-module-search-path
Also, please take a look at http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html It strongly recommends you put an extra level of directory in place so instead of lib.aa, you would refer to it as my_proj.lib.aa.
I had similar problems and here is my advice.
Instead of changing sys.path, better run your test.py from being in proj (i.e. project root) directory. This way project dir will automatically be in sys.path and you will be able to import lib package.
And use absolute imports.
System PATH variable is not used by python import statement. It uses PYTHONPATH, but best way to add new directory to import search path is to modify sys.path.
If this does not help, add to the question your value of sys.path and value returned by os.getcwd().
In Sublime Text 3, abspath it didn't work for me.
I use this instead in the top "__ init __.py" file
Hope it works for you.
from os.path import dirname
from sys import path
path.insert( 0 , dirname( __file__ ) ) ;
from test import aa_test

Categories

Resources