Import from another directory - python

I need to import .py file from another one in another directory (import app2 from app1)
So there is directory tree
app:
dir1:
app1.py
dir2:
app2.py
My problem is almost like Importing from another directory, but this solution doesnt work for me for some reason
Furthermore i've been trying to do like this (app1.py)
from ..dir2 import app2
The error is:
Attempted relative import beyond top-level package
How can i solve this?

Add your additional directories to the system path
import sys
sys.path.insert(0, "/path/to/app1/dir2")
sys.path.insert(0, "/path/to/app2/dir2")

Related

Import file from subdirectory into file in another subdirectory

I have a python project a folder structure like this:
main_directory
main.py
drivers
__init__.py
xyz.py
utils
__init__.py
connect.py
I want to import connect.py into xyz.py and here's my code:
from utils import connect as dc
But I keep getting this error no matter what I do, please help:
ModuleNotFoundError: No module named 'utils'
Update: People are telling me to set the path or directory, I don't understand why I need to do this only for importing file. This is something that should work automatically.
In your utils folder __init__.py should be blank. If this doesn't work, try adding from __future__ import absolute_import in your xyz.py file.
Check your current directory. It must be main_directory.
import os
print("Current working directory is: ", os.getcwd()
if not, you can change using
os.chdir("path/to/main_directory")
also works with relative path
os.chdir('..')
I was also facing same problem when you use row python script so i use the following code at the beginning of the file
import os
import sys
current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
This way it will search the require file at parent directory.
Hope this will work for you also..
You could move your utils folder into drivers, making the path to the to-be imported file a subdirectory of your executing file, like:
main_directory/drivers/utils/connect.py
Alternatively, you could try
from ..utils import connect as dc
This will move up a directory before import.
Lasty, you could add the directory to Path in your script via
import sys
sys.path.insert(0,'/path/to/mod_directory')
For this method, see also this question

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!

How to avoid renaming all imports

I'm trying to use some open source code found on Git. The problem is many files import others modules based on the assumption that all of them are in the root folder. But I created another folder called /logic in the root and therefore, import would be now as
import logic.whatevermodule
what I did in my files (located in the same /logic folder that have been called from start.js, app in Flask).
So all others files still have
import whatevermodule
what caused an error because it can't find it.
The structure now is:
/logic
/whatevermodule
moduleA.py
moduleB.py
mylogic.py
start.py
Start.py calls mylogic.py using import logic
mylogic.py is my file that uses whatevermodule so to use moduleA it should use
import logic.whatevermodule.moduleA
moduleA.py uses moduleB.py but its import is
import whatevermodule.moduleB
what causes error.
What would I do to fix it? ( I don't want to rename all 967 occurrences and don't want to move the folder to the root one.)

Can't import module from sibling directory

I have a Python 3 project that's structured like this:
/project
__init__.py
/models
__init__.py
my_model.py
base_model.py
/tests
__init__.py
test.py
In test.py I want to import my_model. My first attempt was from models import my_model, which threw an ImportError: No module named 'models'. This question recommended adding an __init__.py file to each directory, which didn't help. Another post said to modify the path with:
import sys; import os
sys.path.insert(0, os.path.abspath('..'))
but this throws an error when my_model tries to import from base_model.
This seems really straightforward but I'm stumped. Does anyone have any ideas?
Adding the sibling directory to sys.path should work:
import sys, os
sys.path.insert(0, os.path.abspath('../models'))
import my_model
Use absolute imports everywhere: from project.models import my_model, should work fine from wherever in your project, no need to mess with paths either.
The answer depends on how you launch test.py.
The only way I know to do relative imports is to have the file in a package. For the Python interpreter to know you're in a package is to import it in some way.
Use:
from ..models import my_model
in test.py
And launch the Python Interpreter below the project folder.
You will then be able to import project.tests.test without error.

How do you modify sys.path in Google App Engine (Python)?

I've tried adding the following line to my handler script (main.py), but it doesn't seem to work:
sys.path.append('subdir')
subdir lives in the my root directory (i.e. the one containing app.yaml).
This doesn't seem to work, because when I try to import modules that live in subdir, my app explodes.
1) Ensure you have a blank __init__.py file in subdir.
2) Use a full path; something like this:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))
Edit: providing more info to answer questions asked in a comment.
As Nick Johnson demonstrates you can place those three lines of code in a file called fix_path.py. Then, in your main.py file, do this import fix_path before all other imports. Link to a tested application using this technique.
And, yes, the __init__.py file is required; per the documentation:
When importing the package, Python
searches through the directories on
sys.path looking for the package
subdirectory.
The __init__.py files are required to
make Python treat the directories as
containing packages; this is done to
prevent directories with a common
name, such as string, from
unintentionally hiding valid modules
that occur later on the module search
path. In the simplest case,
__init__.py can just be an empty file, but it can also execute initialization
code for the package or set the
__all__ variable, described later.
It worked for me inserting the new dirs as the first entries in sys.path.
path_changer.py:
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs'))
sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'apps'))
app.py:
import path_changer
from google.appengine.ext.webapp.util import run_wsgi_app
from flask import Flask
import settings
app = Flask('myapp')
app.config.from_object('settings')
from website import views as website_views
run_wsgi_app(app)

Categories

Resources