Importing modules from different directories - python

I have a problem importing a module:
It is under this directory ./dao and the code that calls it is here ./core. Schematically represented as:
rnaspace/
__init__.py
core/
__init__.py
logger.py
dao/
__init__.py
storage_configuration_reader.py
This is the error message:
Traceback (most recent call last): File "logger.py", line 21, in <module>
from rnaspace.dao.storage_configuration_reader import storage_configuration_reader ImportError: No module named rnaspace.dao.storage_configuration_reader
This file it is there /rnaspace/dao/storage_configuration_reader.py and in the same folder the __init__.py file as follows:
""" Package dao
Gathers files that access to the plateform data
"""
If I understood well this question, it should work. I think that the problem is that one is not the subdirectory of the other (or that the path is not exaclly that one), there is a way to go around it? Or need I to apply the solution to this question?
EDIT
The __init__.py file of the rnaspace folder:
import rnaspace.dao.storage_configuration_reader as scr
def update_conf(conf_path, predictors_conf_dir):
scr.update_conf(conf_path, predictors_conf_dir)

from rnaspace.dao.storage_configuration_reader import storage_configuration_reader
That is wrong because there is no "storage_configuration_reader" directory in "dao" directory
This is how it should be:
from rnaspace.dao import storage_configuration_reader
EDIT:
or this way:
import rnaspace.dao.storage_configuration_reader

I finally found the solution in another question, it is using the module imp.
I just needed to add the name of the module, and the absolute path where it was:
imp.load_source("storage_configuration_reader","./rnaspace/dao/storage_configuration_reader.py")

Related

Why does this import give me an error message when trying to import from 2 local modules?

I have the following code structure:
Graph API/
│── main.py
├── helper_functions/
├── defines.py
├── insights.py
insights.py imports 2 functions from defines.py at the beginning:
from defines import getCreds, makeApiCall
It then uses "makeApiCall" for this function:
def getUserMedia( params ) :
// Some code about url endpoints etc.
return makeApiCall( url, endpointParams, params['debug'] ) # make the api call
I want to use the getUserMedia function in the main.py script, so I import it with:
from helper_functions.insights import *
But I get the error:
Traceback (most recent call last):
File "/Users/Graph_API/main.py", line 1, in <module>
import helper_functions.insights
File "/Users/Graph_API/helper_functions/insights.py", line 1, in <module>
from defines import getCreds, makeApiCall
ModuleNotFoundError: No module named 'defines'
What leads to this error? When I use the getUserMedia function within insights.py it works fine. I already tried importing defines.py to main.py as well, but I get the same error.
I am pretty new to programming, so I would really appreciate your help :)
You should replace
from defines import getCreds, makeApiCall
With
from helper_functions.defines import getCreds, makeApiCall
Or
from .defines import getCreds, makeApiCall
You must give a path either from project directory as in the first example, or from the relative path from the insights file by adding a dot.
You could also consider adding init.py to the helper_functions folder. Checkout here: What is __init__.py for?

No module found error when I have added the path

I have a project structure that looks like:
The file greet.py is given as:
def greet_morning(message):
print("Hello, {}", message)
def greet_evening(message):
print("Evening message: {}", message)
and the file msg.py is given as :
import sys
import os
sys.path.append(os.getcwd())
from greet.greet import greet_morning
greet_morning("heyy")
When I try to run msg.py as python message/msg.py, I get an error saying ImportError: No module named greet.greet. I am running this file from the root. Why do I get this error, when I have already added the cwd in the system path?
I think is
from untitled.greet.greet import greet_morning
if still doesnt work, add:
import sys
sys.path.append('../')
edit
I think you may find all the possible solutions here Importing files from different folder
add __init__.py inside greet and msg folder__init__.py
You have missed the file __init__.py in your module.
Just create an empty file __init__.py in greet folder.

Python module not found because import statement is in other file than the one being executed

In the following structure:
src:
model:
- boardmodel.py
- tests.py
exceptions:
- exceptions.py
- visual.py
I'm running visual.py from the terminal. In my boardmodel.py, I have the following import:
from exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
This line causes an error when running visual.py:
Traceback (most recent call last):
File "visual.py", line 3, in <module>
from model.boardModel import Board
File "/Users/sahandzarrinkoub/Documents/Programming/pythonfun/BouncingBalls/balls/src/model/boardModel.py", line 5, in <module>
from exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
ModuleNotFoundError: No module named 'exceptions'
What is the correct way to solve this problem? Should I change the import statement inside boardmodel.py to from model.exceptions.exceptions import ZeroError....? That doesn't feel like a sustainable solution, because what if I want to use boardmodel.py in another context? Let me her your thoughts.
EDIT:
I changed the structure to:
src:
model:
- __init__.py
- boardmodel.py
- tests.py
exceptions:
- __init__.py
- exceptions.py
- visual.py
But still I get the same error.
Place an empty file called __init__.py in each of the subdirectories to make them packages.
See What is __init__.py for? for more details
Then, within boardmodel.py you need to either use relative imports
from .exceptions.exceptions import ...
or absolute ones (from the root of PYTHONPATH)
from model.exceptions.exceptions import ...
When you execute a script from the command line, the directory containing the script is automatically added to your PYTHONPATH, and becomes the root for import statements
You are not at the root of your package so you need relative import.
Add a dot before exceptions:
from .exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
One dot mean "from the current directory"…

How to set a loop to execute modules(*.py) from another packages?

There are several modules under different packages, shown below:
proj
tc_mgr_folder
tcd.py
package1/
__init__.py
subPack1/
__init__.py
module_11.py
module_12.py
module_13.py
subPack2/
__init__.py
module_21.py
module_22.py
...
I would like to write a loop includes those modules(module_11, module_12, module_13, module_21, module_22,...) in tcd.py to test all once. Then save the output messages exported from each module to a text file. Can I do it?
You can get the files in a directory using glob.glob.
You can then import each module using importlib.import_module:
for module in ['os', 'sys']:
try:
importlib.import_module(module)
except ImportError:
print("Could not import module: {}".format(module))

how to import a 'zip' file to my .py

when i use http://github.com/joshthecoder/tweepy-examples ,
i find :
import tweepy
in the appengine\oauth_example\handlers.py
but i can't find a tweepy file or tweepy's 'py' file, except a tweepy.zip file,
i don't think this is right,cauz i never import a zip file,
i find this in app.py:
import sys
sys.path.insert(0, 'tweepy.zip')
why ?
how to import a zip file..
thanks
updated
a.py :
import sys
sys.path.insert(0, 'b.zip')
import b
print b
b.zip:
b file
|-----__init__.py
|-----c.py
c.py:
cc='ccccc'
the error is :
> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py"
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 9, in <module>
import b
ImportError: No module named b
updated2
it is ok now ,
the error's reason is : i rename b.rar to b.zip
The name of the zip file is irrelevent when searching for modules - this allows you to include version numbers in the file name, such as my_b_package.1.2.3.zip.
To import from a zip file, you need to replicate the full package structure within it. In this case, you need a package b, with the __init__.py and c.py modules.
I.e:
b.zip
|
| -- b <dir>
| -- __init__.py
| -- c.py
You don't import zip files, you add them to sys.path so that you can import modules within them. sys.path is a list, and as such the normal list methods/operations (e.g. .append()) all work on it.

Categories