Importing from one module to another - python

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

Related

Cannot import script functions from another script

I've the following hierarchy:
.root
/program/main.py
/functions/myfunctions.py
And using my main.py I want to use the functions present in myfunctions.py script. For that I've defined my PYTHONPATH AS ./root/functions and I have this as the import on my script:
from functions import myfunctions as func
But I'm getting this error:
ModuleNotFoundError: No module named 'functions'
How can I solve this?
Thanks
You defined your PYTHONPATH as ./root/functions, so everything(modules/packages) "inside" that directory is recognizable by Python. ./root/functions directory is gonna get inserted to the sys.path. These paths are where Python loader checks to find modules and packages.
Just import the myfunctions.py:
import myfunctions as func
If you had defined PYTHONPATH as ./root, then you would have access to functions directory. (It became your namespace package for more information)
Import builtin module pathlib
Add the following code in your myfunctions.py
from pathlib import Path
Path(__file__).resolve().parent.parent

import .py script on same folder

I've a python file named sample.py which has some functions and another python file from which I want to access the functions of the sample.py. I've tried the code below which is working fine if I include the directory in the import statement.
from Integrated.sample import *
But the folder can't be the same for my application. Also, I referred another problem in stackoverflow similar to my issue, tried one of the answers
from .sample import *
which gives the following error
ModuleNotFoundError: No module named '__main__.crypto'; '__main__' is not a package
directory structure:
-module
--__init__.py
--sample.py
--tester.py
Hoping for a solution
Thanks in advance
If they are in the same module, you can directly import the file as given below. Works for me.
sample.py
def myfun():
print("Sample")
tester.py
from sample import myfun
myfun()
Output
$ python3 tester.py
Sample
If I understand you question correctly, you would like to import a python module from another python folder.
I see you already have a __init__.py file that is needed to declare this folder is a python package.
Navigate to the file where you want to import the module.
from root.parent.folder.file import function_name
other way of doing it
import sys
import os
sys.path.append(os.path.abspath("/home/helloworld"))
from helloworld import *
Hope this helps.

Python load_source import not found

I am not a proficient Python coder, hence this might be a basic question:
In my main python code, I load a python code file using (dynamically)
import imp
model = imp.load_source('name','c:/modeldir/modelfile.py')
modelfile.py does an import on the top:
from MyLib import MyLib
MyLib.py is in the same folder as modelfile.py
I get:
ImportError: No module named 'MyLib'
I have also tried:
import os
os.chdir('c:/modeldir')
just before the imp.load_source, did not help.
EDIT:
I am using Python 3.5.2
I've added an empty __init__.py file in 'c:/modeldir'
How to solve this?
The following made it work
sys.path.append('c:/modeldir')
This adds the folder to the python import path and then MyLib can be found

Python not recognising another file

I am creating a python module. To test it i put the file in the same directory and then wrote the code
import mymodule
mymodule.dofunction
python then said >>>no module named mymodule but they are in the same directory.
Adapting from previous answer here. Explicitly state that you want to use the current directory.
Also, consider that you need an "__init__.py" file in each directory you are importing from.
import os, sys
lib_path = os.path.abspath('.')
sys.path.append(lib_path)
import mymodule
More information on the import system here.

trying to import a *.pyc as a module

I have a python script that is trying to import another script somewhere in the file-system (path is only known at runtime).
To my understanding I need to use the imp module and this might work, but when loading the module I get an error that modules used by the imported module are not found.
Heres the code:
importer.py:
import imp
imp.load_compiled("my_module","full_path_to_my_module\\my_module.pyc")
my_module.py:
import sys
import another_module
When I run importer.py I get htis error message:
ImportError: No module named another_module
Whats going wrong here ?
I suspect that when 'importer.py' is loading 'my_module.pyc' hes also trying to load 'another_module' (thats good) but is looking in the wrong place (eg not 'full_path_to_my_module')
EDIT:
I tried adding 'full_path_to_my_module' to the system path:
import imp
import sys
sys.path.append(full_path_to_my_module)
imp.load_compiled("my_module",full_path_to_my_module+my_module)
But I still get the same error
Maybe I do something thats not necessary - Here's my goal:
I want to be able to use all functionality of 'my_module.pyc' inside 'importer.py'. But the location of 'my_module.pyc' is given as a parameter to 'importer.py'.
imp.load_compiled returns the compiled module object, it is different to the import statement which also binds the module to a name
import imp
my_module = imp.load_compiled("my_module", "full_path_to_my_module/my_module.pyc")
Then you can do something like:
my_module.yayfunctions('a')
Complete example session:
$ cat /tmp/my_module.py
def yayfunctions(a):
print a
$ python -m compileall /tmp/my_module.py
$ ls /tmp/my_module.py*
my_module.py my_module.pyc
$ python
>>> import imp
>>> my_module = imp.load_compiled("my_module", "/tmp/my_module.pyc")
>>> my_module.yayfunctions('a')
a
Edit regarding comment (ImportError: No module named another_module), I assume the error is caused by the code in my_module.pyc, and the another_module.py lives in the same directory
In that case, as others have suggested, it's simpler to just add the directory containing my_module to sys.path and use the regular import mechanism, specifically __import__
Here's a function which should do what you want:
import os
def load_path(filepath):
"""Given a path like /path/to/my_module.pyc (or .py) imports the
module and returns it
"""
path, fname = os.path.split(filepath)
modulename, _ = os.path.splitext(fname)
if path not in sys.path:
sys.path.insert(0, path)
return __import__(modulename)
if __name__ == '__main__':
# Example usage
my_module = load_path('/tmp/my_module.py')
my_module.yayfunctions('test')
It is since at the scope of import another_module your "full_path_to_my_module" isn't known.
Have you tried to add the path to known paths instead, i.e.:
import sys
sys.path.append("full_path_to_my_module")
You don't actually need to use the imp module to load pyc modules.
An easy way to try it out is to make two python modules, one importing from the other and run it. Delete then the imported .py file so you only get the .pyc file left: when running the script the import will work just fine.
But, for importing py files from random directories, you may want to add that directory to the python path first before importing it.
For instance:
import sys
sys.path.insert(0, "/home/user/myrandomdirectory")
Loading pyc files works the exact same way as loading a py file except it doesn't do a compile step. Thus just using import mymodule will work as long as the version number of the pyc is the same as the python you're running. Otherwise you'll get a magic number error.
If you module isn't in your path you'll need to add that to sys -- or if its a subdirectory, add a __init__.py file to that directory..

Categories