How to access module from subdirectory in Python - python

I have a folder structure like so:
/mylib/
/mylib/__init__.py
/mylib/my_class.py
/mylib/tests/test_my_lib.py
In my test, I have:
from mylib import MyClass
import unittest
I'm getting:
File "test_edgecast_mcc_client.py", line 1, in <module>
from mylib import MyClass
ImportError: No module named mylib
Which, I think, makes sense because the import would be looking inside the tests directory for mylib when it should be looking in ../mylib?
Can anyone share some light on how to get the import to work properly?

I believe your tests package needs an __init__.py file too

Add primary directory to $PYTHONPATH. You can do it from your test_my_lib.py using something like this:
import sys
import os.path
d = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, d)

try using this from command line and see if that eliminates the error
export PYTHONPATH="$PYTHONPATH:/path/to/mylib/"

Related

Import script from another script in python

I have imported a repo using git and when I try to run a file, it shows that "it could not be resolved".
The running script has:
import craft_utils
import test
import imgproc
import file_utils
The imported things are all script.
I have attached the screenshots for the error and hierarchy.
How can I solve this? Thanks.
try adding an empty file named __init__.py in the root folder CRAFT-pytorch (instead of the basenet folder)
create a empty file named __init__.py
it would solve the issue
Add a file inside of the folder called __init__.py
First you need to create an empty file named __init__.py in the folder CRAFT-pytorch
Second add these line at the top of the file you're trying to running, before the imports:
import os
import sys
import inspect
app_path = inspect.getfile(inspect.currentframe())
main_dir = os.path.realpath(os.path.dirname(app_path))
sys.path.insert(0, main_dir)
import craft_utils
import test
import file_utils

What is the correct way to import a custom module under library that is part of a custom role

I created an Ansible custom module that lives embedded in a custom Ansible role
This is the files tree:
my-role/
library/
my_module.py
test/
units/
test_module.py
I want to test my_module so I wanted to import and start testing
I tried several things under the test_module.py
Tried to do something like this:
target = __import__("my_module")
myfunc = target.my_function
also, I tested with "library/my_module.py"
and I got
Traceback (most recent call last):
File "test/units/test_module.py", line 1, in <module>
target = __import__("library/my_module.py")
ModuleNotFoundError: No module named 'library/my_module'
I tried to move my test_module.py in the same directory of my_module.py
my-role/
library/
my_module.py
test_module.py
I got the same error but it says is not a package
Any idea, documentation, or a guide I can follow?
Thanks
One way is to add the path of the package to sys.path. I'm not sure if this is the recommended way, but this way has always worked for me.
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
Then, you should be able to import in your test module.
import library.my_module

Importing from one module to another

I have two modules in the same directory:
PDSC2.py and db_layer.py
I want to import a class named DBLayer from db_layer.py so I write:
from db_layer.py import DBLayer
But I get an error:
ModuleNotFoundError: No module named 'db_layer'
Does somebdy have an idea what i'm doing wrong?
first of all assume that this python files in the same directory and then remove extension from your code.
from db_layer import DBLayer
or:
from db_layer import *
Is the directory in a place where python searches for modules, python path? Do you have a __init__.py in the directory (it can be blank)?
You need to paste the program file db_layer.py in the \Python\Python36-32\Scripts directory
, then use from db_layer import DBLayer or from db_layer.py import DBLayer to call the desired class in the python program .
Actually sometimes changing the directory of the called module to \Python\Python36-32\Scripts solves these types of problems easily.
This is the solution that worked for me:
import sys
sys.path.append("C:\\Users\\carmel.han\\AppData\\Roaming\\QGIS\\QGIS3\\profiles\\default\\python\\plugins/filterparcel")
from db_layer import DBLayer

Python unittest failing to resolve import statements

I have a file structure that looks like the following
project
src
__init__.py
main.py
module.py
secondary.py
test
test_module.py
module.py
import secondary
x = False
secondary.py
pass
test_module.py
from unittest import TestCase
from src import module
class ModuleTest(TestCase):
def test_module(self):
self.assertTrue(module.x)
Invoking python3 -m unittest discover in /project/ gives an error:
File "/Users/Me/Code/project/test/test_module.py", line 6, in <module>
from src import module
File "/Users/Me/Code/project/src/module.py", line 1, in <module>
import secondary
ImportError: No module named 'secondary'
What can I do so that secondary.py is imported without error?
In Python 3 (and Python 2 with from __future__ import absolute_import), you must be explicit about what module you want when importing another module from the same package. The syntax you're using in module.py (import secondary) only works if secondary is a top-level module in a folder in the Python module search path.
To explicitly request a relative import from your own package, use from . import secondary instead. Or, make an absolute import, using the name of the package as well as the module (from src import secondary, or import src.secondary and use src.secondary elsewhere the module instead of just secondary).
Try adding this to the top of the test file
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Note: Depending on the project structure we have to specify the root folder

Python imports with __init__.py

No matter how I structure the imports in the code files and in the __init__.py files, I can't seem to get it right for executing the program and running the tests using pytest. How do I need to write the imports when my project structure looks like this:
src/
__init__.py
VocableFileWriter.py
WordListHelper.py
WordListReader.py
XLDAttributeValueAdder.py
exceptions/
__init__.py
XMLInvalidException.py
XMLParseException.py
gui/
__init__.py
GTKSignal.py
XLDAttributeValueAdderWindow.py
test/
__init__.py
test_XLDAttributeValueAdder.py
xmlparser/
__init__.py
XMLParser.py
Currently I have them like this:
In the __init__.py files I have the imports like this (src/__init__.py):
from src import *
from src.exceptions import *
from src.xmlparser import *
and in a subpackage (src/xmlparser/__init__.py):
from src.xmlparser import *
So I guess those are project-absolute paths to the modules.
In the code files themselves I import like this:
import os
import sys
from VocableFileWriter import VocableFileWriter
from XLDAttributeValueAdder import XLDAttributeValueAdder
However, when I execute the code from the directory above src using:
./src/main.py
It tells me that:
Traceback (most recent call last):
File "./src/main.py", line 6, in <module>
from VocableFileWriter import VocableFileWriter
File "/home/xiaolong/Development/PycharmProjects/xld-attribute-value-adder/src/VocableFileWriter.py", line 2, in <module>
from XMLInvalidException import XMLInvalidException
ImportError: No module named 'XMLInvalidException'
It used to be a PyCharm project, but I couldn't get it to run with the imports structure PyCharm used when not using PyCharm but running it from the terminal, so I decided I wanted to take the whole import stuff into my own hands. So don't get confused by it being in a PyCharm directory.
I also want to be able to execute the tests using for example:
py.test src/test/test_XLDAttributeValueAdder.py
How do I solve this mess?
Edit#1:
I had the program running once, but then the test complained about missing modules, probably because it's in another subdirectory and I tried so many configurations, that I don't know how I had the program running anymore. If possible please add some explanation why a certain structure is correct and works for both, tests and the program itself.
EDIT#2:
I've managed to get the tests running now, but now the program doesn't run anymore.
I emptied all the __init__.py files and used only project-absolute paths in the code files like this (src/test/test_XLDAttributeValueAdder.py):
from src.VocableFileWriter import VocableFileWriter
from src.WordListHelper import WordListHelper
from src.WordListReader import WordListReader
from src.XLDAttributeValueAdder import XLDAttributeValueAdder
from src.exceptions.XMLInvalidException import XMLInvalidException
from src.exceptions.XMLParseException import XMLParserException
from src.xmlparser.XMLParser import XMLParser
from src.test.path_helper import go_up
from src.test.path_helper import go_in
and in the main.py:
from src.VocableFileWriter import VocableFileWriter
from src.XLDAttributeValueAdder import XLDAttributeValueAdder
the output of ./src/main.py:
./src/main.py
Traceback (most recent call last):
File "./src/main.py", line 6, in <module>
from src.VocableFileWriter import VocableFileWriter
ImportError: No module named 'src'
EDIT#3:
I've tried the relative import way like this:
main.py moved one directory up
The structure now looks like this:
main.py
src/
__init__.py
VocableFileWriter.py
WordListHelper.py
WordListReader.py
XLDAttributeValueAdder.py
exceptions/
__init__.py
XMLInvalidException.py
XMLParseException.py
gui/
__init__.py
GTKSignal.py
XLDAttributeValueAdderWindow.py
test/
__init__.py
test_XLDAttributeValueAdder.py
xmlparser/
__init__.py
XMLParser.py
__init__.py files empty
main.py file gets relative
Imports look like this:
import os
import sys
from .src.VocableFileWriter import VocableFileWriter
from .src.XLDAttributeValueAdder import XLDAttributeValueAdder
When I try to run the main.py file:
Traceback (most recent call last):
File "main.py", line 6, in <module>
from .src.VocableFileWriter import VocableFileWriter
SystemError: Parent module '' not loaded, cannot perform relative import
However, there is a __init__.py file in the same directory as the main.py file, also empty.
You'd better use relative imports.
When doing from src import * in src/__init__.py you'll only import anything you've defined before calling the import. Most likely that's just nothing. If you've defined the __all__ variable, you'll get the submodule from it, but maybe also an AttributeError if a variable hasn't been defined yet.
So instead import the modules you need explicitly where you need them like
from .VocableFileWriter import VocableFileWriter
from .exceptions.XMLInvalidException import XMLInvalidException
or lets say within src/gui/GTKSignal.py
from ..exceptions.XMLInvalidException import XMLInvalidException
Also you could use project-absolute paths like mentioned in your Edit#2.
Furthermore you've a problem with your path when calling ./src/main.py. In this case the directory containing src is not in the path. Instead ./src/ is in the path. Therefore python doesn't consider it a package anymore and since there's no other package with that name available, the import fails.
Instead put your main.py module in the same directory like the src package or call it as a module with python -m src.main. Doing so you could also rename it to src/main.py and call the package instad with python -m src.
When using the first approach, main should use an absolute import structure. Just think of it as a module you put anywhere on your computer, while your src package is somewhere else, where it can be found by Python, like any other module or package installed by the system. It's not different, when it's located besides the package itself, since the current directory is in sys.path.
main.py
import os
import sys
from src.VocableFileWriter import VocableFileWriter
from src.XLDAttributeValueAdder import XLDAttributeValueAdder

Categories