Importing multiple python files in subfolders - python

I want to import a python file Loader within a subfolder sub1. This file that I want to import, imports another file detector within that same subfolder. However, Loader gives the following error:
ModuleNotFoundError: No module named 'detector'
I've tried using the exec command in Python and
import sub1.Loader
The folder structure looks like this:
Project
|
+-- File_for_loading_Loader.py
|
+-- sub1
|
+-- __init__.py
+-- Loader.py
+-- detector.py
Can anyone help?
Edit
I now use:
import subprocess
subprocess.call(["python", "Loader.py"], cwd="sub1")
which does the trick nicely. No need for relative imports etc.

Since you created sub1 as module you have to import files from it always like sub1.<module_name>.
So for you it should be from sub1.detector import detect_faces in your Loader.

You need to import loader in File_for_loading_Loader.py by using import sub1.Loader as abc.
And in Loader.py you need to import detector by using import sub1.detector as xyz.

Related

Import subfolder file from Jupyter Notebook

With a folder structure like this:
~/
+-- some_module/
| +-- subfolder/
| | +-- submodule.py
| +-- helpers.py
| +-- api.py
+-- notebook.ipynb
This is the content of api.py:
from subfolder.submodule import submodule_fun
def print_something(string):
print(submodule_fun(string))
# ...
if __name__ == '__main__':
run()
And submodule.py:
from helpers import helper_fun
def submodule_fun(string):
stuff = helper_fun(string)
return stuff
This works perfectly fine when running python api.py from the command line. The submodule.py file is simply using some function from helpers.py and no drama needed.
However, I also want to be able to use submodule.py from notebook.ipynb which lives outside some_module. When I add the following lines in this notebook:
from some_module.subfolder import submodule
I get the following error:
~/some_module/subfolder/submodule.py in <module>
---> from helpers import helper_fun
ModuleNotFoundError: No module named 'helpers'
I tried packaging all of some_module into a proper module using setuptools but I'm running into weird errors, apparently because the module is not living directly in the repository's root.
Without resorting to packaging some_module, would there be a way to be able to access submodule.py from the notebook.ipynb in this scenario?
Try adding some_module to your PATH or PYTHONPATH environment variable, either through OS or programatically (shown below)
import sys
import os
abspath = r"c:\your\path\to\some_module"
sys.path.append(os.path.abspath(abspath ))
from some_module.subfolder import submodule
As an alternative to packaging, you can use poetry to manage your dependencies, virtual environment, and it will install your project into the environment without actually needing to produce a package.

How to use own Python Packages within the own packages? ModuleNotFoundError: No module named

I created some code using the following structure:
├── project
| ├── .vscode
| | └── settings.json
| ├── packages
| | ├── __init__.py
| | ├── module_one.py
| | └── module_two.py
| └── main.py
module_one content
def functionModuleOne():
print('functionModuleOne')
module_two content
import module_one
module_one.functionModuleOne()
def functionModuleTWO():
print('functionModuleTWO')
main content
from package import module_two
The point is that I'm trying to import the "module_one" inside the "module_two". I got some erros because, apparently, I should specify the path of the modules in a .vscode/settings.json. So, I did it
There is what is inside the json:
{
"python.analysis.extraPaths": [".\\package"]
}
Then, it apparently worked fine. I executed the file "module_two.py" and I got no errors.
However, when I tried to execute the file "main.py", I got the following error: ModuleNotFoundError: No module named "module_one".
I need that structure because "module_two" needs to import functions from "module_one" and "main" needs to import functions from "module_two".
I really don't know what is happening. I tried everything and searched for it on web, but without good results.
I'd be so glad if some of you could help me.
The reason is that when importing methods in other files, VS Code starts to search from the parent folder of the imported file by default. Obviously, in the file "main.py", it cannot find the file "module_one" according to "import module_one".
You could refer to the following methods:
Please use the following code in the file "module_two":
import sys
sys.path.append("./")
from emo.module_one import functionModuleOne
functionModuleOne()
def functionModuleTWO():
print('functionModuleTWO')
"from emo.module_one import functionModuleOne": ("main.py" can find "module_one" according to this path.),
"sys.path.append("./")": Add the path of the file "module_one" to the path of "module_two".
Run main.py:
I guess the error is shown because of only letter...
Edit this part and give it a try:
from packages import module_two
The error is because you saved the folder with the name 'packages' and you are trying to import module_two from 'package' so it's giving a error..
Let me know if it works :)

"ModuleNotFoundError" when importing modules inside package

I am trying to make my own package so that I can use the files in a different folder. This package contains a few different modules and then the main module that imports all the others inside it. For example:
Folder
|- main.py
|- other.py
|- something.py
|- __init__.py
Inside the main.py I have the imports:
import other
import something
and it works just fine when running the file itself; however, I added the __init__.py file and tried to import it into a different folder. The package is recognized, but the main.py gives me the following error:
Exception has occurred: ModuleNotFoundError No module named
'univariate'
File "C:...\stats.py", line 8, in
import univariate
File "F:...\testing.py", line 7, in
from stats import stats
For clarification, the actual main file is called stats.py. This is my first experience trying to make a package so I might be missing something. Thank you.
You need to change your imports into relative imports
import .other
import .something
or to change it to absolute imports rooted to your project folder
import x.y.other
import x.y.something
you can read here about the imports
When you have a module that you're trying to import you don't need the ".py" part.
Having a folder with a init.py file (even a blank one) means that a project that contains that folder can import from it.
/myproject
| - /mymodule
| - |- stats.py
| - |- other.py
| - |- something.py
| - |- __init__.py
| - main.py
then in main.py all you need to do is import mymodule or from mymodule import stats
I always hate to FTFM someone, but here's a link to how to build packages from the official documentation. But, where this really starts to shine is when you need to package your module so that someone else can run it Digital Ocean has a pretty good tutorial here.

Python import doesn't work when file is imported

I am having difficulties to understand how the python importer works..
I have a python script (fractalDimension.py) that imports a submodule ("greedyColoring.py") using:
from boxCovering.greedyColoring import *
It works fine when I call it directly:
python fractalDimension.py
The problem began when I moved the script to a folder and added a main script which imports the fractalDimension.py because now the import of the boxCovering sub module doesn't work.
In the main script I call the fractalDimension method:
import fractality.fractalDimension as fd
fd.calculate()
but when I run
python main.py
I get the following error
Traceback (most recent call last):
File "main.py", line 5, in <module>
import fractality.fractalDimension as fd
File "fractalDimension.py", line 11, in <module>
from boxCovering.greedyColoring import *
ImportError: No module named 'boxCovering'
Directory layout:
main.py
fractalDimension/
|
+-- __init__.py
+-- fractalDimension.py
+-- boxCovering/
|
+-- __init__.py
+-- greedyColoring.py
Both init files are empty
Why python cannot find the boxCovering module?
The error is due to the fact that python is searching for a top-level package called boxCovering inside the PYTHONPATH and none exists (you have only a sub-package inside the current directory, but this isn't searched).
When you want to import a subpackage/submodule you want to use a(n explicit) relative import:
from .boxCovering.greedyColoring import *
note the . (dot) at the beginning.
Alternatively use the absolute import:
from fractality.fractalDimension.boxCovering.greedyColoring import *
In python2 the import allowed an implicit relative import, which is what you are trying to do. In that case the import:
from boxCovering import X
done in the way you are doing could have two different meanings:
import of the subpackage boxCovering of the fractalDimension package
import of the top-level package boxCovering
In python3 (see the What's new? and relevant PEP 0328) they decided that such an import always has the second meaning. If you want a relative import you have to explicitly state so by using the relative syntax, which uses a dot at the beginning of the module name.
Each dot means go to one directory above so . means the current directory while .. means the parent directory (as in unix paths) etc.
You can enable this semantics on python2 adding:
from __future__ import absolute_import
at the top of your files.

How to import a Python module from a sibling folder?

I have gone through many Python relative import questions but I can't understand the issue/get it to work.
My directory structure is:
Driver.py
A/
Account.py
__init__.py
B/
Test.py
__init__.py
Driver.py
from B import Test
Account.py
class Account:
def __init__(self):
self.money = 0
Test.py
from ..A import Account
When I try to run:
python Driver.py
I get the error
Traceback (most recent call last):
from B import Test
File "B/Test.py", line 1, in <module> from ..A import Account
ValueError: Attempted relative import beyond toplevel package
This is happening because A and B are independent, unrelated, packages as far as Python is concerned.
Create a __init__.py in the same directory as Driver.py and everything should work as expected.
In my case adding __init__.py was not enough. You also have to append the path of the parent directory if you get module not found error.
root :
|
|__SiblingA:
| \__A.py
|
|__SiblingB:
| \_ __init__.py
| \__B.py
|
To import B.py from A.py, you have to do the following
import sys
# append the path of the parent directory
sys.path.append("..")
from SiblingB import B
print("B is successfully imported!")
The reason for
ValueError: Attempted relative import beyond toplevel package
is that A is the same directory level as Driver.py. Hence, ..A in from ..A import Account is beyond top-level package.
You can solve this by create a new folder named AandB together with __init__py in this new folder, and then move A and B folders into AandB folder. The directory structure is as following:
Correspondingly, the content in Driver.py should be modified as from AandB.B import Test.

Categories