I have a problem with python directories.
I have structure like:
python
modules
algorithms
cyphers
morse.py
tests
algorithms
cyphers
test_morse.py
When I try to import module in test I get a module not found error.
I am trying to import like:
parent_dir_name = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(parent_dir_name + "/../../../")
from modules.algorithms.cyphers.morse import *
I have also init files in all directories.
I am trying to run tests like:
> python -m unittest discover ./tests
It is customary to use relative imports
from ....modules.algorithms.ciphers.morse import *
This ensures that you import the right Morse file, otherwise you risk importing some module named Morse that you've installed.
Here's two examples to illustrate relative imports, say you have a file named simulation.py that has the line
from .animals import Herbivore
In it. This will import the Herbivore class from a file in the same directory as the simulation.py file
Now imagine that you have a folder named tests, in this folder you have a file named test_animals.py, which has the line
from ..animals import Herbivore
This will import the Herbivore class from a file named animals.py located in the folder above the tests folder.
Finally, note that (at least for Python 3.6) can't run a file that uses relative imports, only import it.
If you mark the directories as modules with __init__.py, you should just be able to import modules via
from modules.algorithms.cyphers import morse
Related
I am currently trying to import some python files inside of a folder named "modules". My file structure is as follows:
src
- classes
- modules
- image generator ( the file where I am trying to import modules)
Error:
from modules.processing import StableDiffusionProcessingTxt2Img, process_images
ModuleNotFoundError: No module named 'modules'
from modules.processing import StableDiffusionProcessingTxt2Img, process_images
I have attempted to add both an __init__.py in my classes folder, as well as my modules folder, but unfortunately that did not resolve any of my problems.
I have verified that the files I am trying to import are infact in my modules folder.
You must import from the projects' root directory. Assuming src/ is the root directory, you must import as follows:
from classes.modules.processing import StableDiffusionProcessingTxt2Img, process_images
Since you are trying to import functions from another python file that's located on another folder, it is having a hard time figuring out where it is located.
Try this:
import sys
sys.path.insert(1,'/src/classes/modules')
import (your python file)
Make sure you keep the above code on the python file where you are trying to import functions from other .py files
Remember, the path is the absolute path from root. Not sure how many more layers you have before src, put accordingly.
Also, the last line is import python file. So, if you have x.py inside modules, try import x. Then you will be able to use functions inside there.
I have made a small programming language and seperated the Lexer, Parser, and Interpreter into different files. Now I would like those files to be in a sub directory Source. I have Shell.py that uses them. In short, this is the structure.
Language -{
Source -{
Main.py
Lexer.py
Parser.py
Interpréter.py
Shell.py
In shell .py, I want to import main.py, which in turn imports the Lexer, parser, and interpreter.
So:
#Shell.py
import Source.Main
Main.run(some code)
#Main.py
from Lexer import Lexer
.... Parser
.... Interpreter
When I run Main.py everything works, but when I run Shell.py it comes up with this:
File Source/Main.py, line 1 in <module>
from Lexer import Lexer
ImportError: No module named ‘Lexer’
EDIT:
There is an _init_.py in the Source directory.
I am not trying to import multiple files from the sub directory, just one that procedes to import others.
Importing a file does not automatically import all the packages you imported in the file. Basically, when you imported Main.py, you didn't import the packages that Main.py imports. You need to manually import all of the packages in that folder.
EDIT: Based on a discussion in the comments, you need to change import omega to from Source import omega assuming Source is what you called the folder where your other files is stored.
I am building a discord bot and I am having trouble importing the code with the functions that I want to test.
When I run my MemberRepositoryTest.py file it gives me the following error:
ModuleNotFoundError: No module named 'Src'
MemberRepositoryTest.py (/Tests/Src/Repositories/)
import pytest
from Src.Repositories import MemberRepository # <--- This line is failing.
# TODO: Implement tests
My folder structure is this on this link - https://imgur.com/a/Rh65iJY
The tests structure is:
Tests/Src/Repositories/MemberRepositoryTest.py (Mirrors Src)
I am unsure why it is not finding my modules so I can import the classes and functions.
From my research online I think it may be a problem with my init.py files. However, being new to Python, I do not understand this fully. I read the Python documentation which explained it creates a package with the files inside as the modules. This means I have imported each file in the directory to the init.py file. However, I am still getting this issue.
Init file (on root directory):
import Src
Init file (/Src/):
import Cogs
import Entities
import Models
import Queries
import Repositories
import AppConfig
import DatabaseConnection
Init file (/Src/Repositories):
import GuildRepository
import MemberRepository
I run this from the root directory of the project (documents/rush_bot). The command I run to execute the test file is pytest Tests/Src/Repositories/MemberRepository.py
My Python Path Environment is:
C:\WINDOWS\SYSTEM32\python27.zip
C:\Python27\DLLs
C:\Python27\lib
C:\Python27\lib\plat-win
C:\Python27\lib\lib-tk
C:\Python27
C:\Python27\lib\site-packages
Python is failing to find your package since it is not in the PYTHONPATH.
You can either add your project folder to the PYTHONPATH or .. If you add . then Python will always look for packages inside the current directory.
By the way, in this Init file (/Src/Repositories) you are importing modules without the full path.
import Src.Repositories.GuildRepository
import Src.Repositories.MemberRepository
I have a git project ('submodule_folder') cloned as a submodule inside my git project ('my_project') with the following file structure:
my_project
submodule_folder
submodule_folder2
__init__.py
submodule_file.py
file_to_import.py
my_file1.py
my_file2.py
I want to import 'file_to_import.py' from 'my_file1.py' but 'file_to_import.py' imports 'submodule_file.py'.
When doing the following import from 'my_file1.py' I get a ModuleNotFoundError: No module named 'submodule_folder2'.
from submodule_folder import file_to_import
Using Python3, is there any way to do this import without writing sys.path.append('submodule_folder/') in each of my files? I'd prefer not to modify the content of 'submodule_folder'.
If file_to_import.py has
from submodule_folder2 import submodule_file
it worked in Python 2 because in Py2 it was implicit relative import. Python 3 disabled this import mode, it only allows absolute import or explicit relative import. Either
from submodule_folder.submodule_folder2 import submodule_file
or
from .submodule_folder2 import submodule_file
I am trying to import a module from a python file that is in a sibling folder. I read several similar questions here and tried to apply solutions listed there, but I wasn't able to solve the problem.
The structure is as follows:
parentfolder/gfolder/codefolder/fileA.py
parentfolder/gfolder/utilfolder/util.py
gfolder, codefolder and utilfolder all have an __init__.py.
I'm trying to do in fileA.py:
import gfolder.utilfolder.util as util
I also tried adding before the import statement:
sys.path.append(".../parentfolder/")
And that didn't work either:
import gfolder.utilfolder.util as util
ModuleNotFoundError: No module named 'gfolder'
The solution in a similar question says to include __init.py__ in the directories, which I already have.
EDIT:
Now both sys.append and sys.insert work and the problem was that I included a slash at the end of the path. When I took it out, everything worked.
First of all, let me describe you the differences between a Python module & a Python package so that both of us are on the same page. ✌
A module is a single .py file (or files) that are imported under one import and used. ✔
import aModuleName
# Here 'aModuleName' is just a regular .py file.
Whereas, a package is a collection of modules in directories that give a package hierarchy. A package contains a distinct __init__.py file. ✔
from aPackageName import aModuleName
# Here 'aPackageName` is a folder with a `__init__.py` file
# and 'aModuleName', which is just a regular .py file.
Therefore, when we have a project directory named proj-dir of the following structure ⤵
proj-dir
--|--__init__.py
--package1
--|--__init__.py
--|--module1.py
--package2
--|--__init__.py
--|--module2.py
🔎 Notice that I've also added an empty __init__.py into the proj-dir itself which makes it a package too.
👍 Now, if you want to import any python object from module2 of package2 into module1 of package1, then the import statement in the file module1.py would be
from proj-dir.package2.module2 import object2
# if you were to import the entire module2 then,
from proj-dir.package2 import module2
I hope this simple explanation clarifies your doubts on Python imports' mechanism. 😊
As Andrew Cox answerd int the following thread Import a module from a relative path
You can add the subdirectory to your Python path so that it imports as a normal script
import sys
sys.path.insert(0, <path to gfolder>)
import gfolder
you can also add the directory to the PATH var of the Linux system (I use it while I'm working on a project, at the end i modified the PATH to it's origin value)
if you maintain the following structre than it is working out side the box
parentfolder/gfolder/codefolder/fileA.py
parentfolder/gfolder/utilfolder/util.py
parentfolder/gfolder/main.py
run main.py