Import python module NOT on path - python

I have a module foo, containing util.py and bar.py.
I want to import it in IDLE or python session. How do I go about this?
I could find no documentation on how to import modules not in the current directory or the default python PATH.
After trying import "<full path>/foo/util.py",
and from "<full path>" import util
The closest I could get was
import imp
imp.load_source('foo.util','C:/.../dir/dir2/foo')
Which gave me Permission denied on windows 7.

One way is to simply amend your path:
import sys
sys.path.append('C:/full/path')
from foo import util,bar
Note that this requires foo to be a python package, i.e. contain a __init__.py file. If you don't want to modify sys.path, you can also modify the PYTHONPATH environment variable or install the module on your system. Beware that this means that other directories or .py files in that directory may be loaded inadvertently.
Therefore, you may want to use imp.load_source instead. It needs the filename, not a directory (to a file which the current user is allowed to read):
import imp
util = imp.load_source('util', 'C:/full/path/foo/util.py')

You could customize the module search path using the PYTHONPATH environment variable, or manually modify the sys.path directory list.
See Module Search Path documentation on python.org.

Give this a try
import sys
sys.path.append('c:/.../dir/dir2')
import foo

Following phihag's tip, I have this solution. Just give the path of a source file to load_src and it will load it. You must also provide a name, so you can import this module using this name. I prefer to do it this way because it's more explicit:
def load_src(name, fpath):
import os, imp
return imp.load_source(name, os.path.join(os.path.dirname(__file__), fpath))
load_src("util", "../util.py")
import util
print util.method()
Another (less explicit) way is this:
util = load_src("util", "../util.py") # "import util" is implied here
print util.method() # works, util was imported by the previous line
Edit: the method is rewritten to make it clearer.

Related

import error attempting to import from the directory above

Not a python developer and I am clearly missing something fundamental here. Using Python 3.10.7 and i am getting an error:
from ..class_one import ClassOne
ImportError: attempted relative import beyond top-level package
when attempting to execute python run_me.py script in the example below
I have the following structure with following import statements
\Project
\data_processor
data_process.py
from ..class_one import ClassOne <--getting an error here
run_me.py
from data_processor.data_process import DataProcess
class_one.py
interesting that when i type a line from ..class_one import ClassOne in data_process.py my IDE thinks its completely legit and intellisence works, suggesting that i import ClassOne.
Most of the solutions imply Python earlier than v3.3 (changed the way packages are handled), which isn't the case here.
Python does not allow relative imports beyond the top-level package. This is why you are seeing the ImportError: attempted relative import beyond top-level package error...
Try to use absolute import, like this:
from Project.class_one import ClassOne
You can also move the class_one module to a package within the current project, you can create a new package and move the class_one module to it. Then, you can use a relative import to import the ClassOne module:
\Project
\data_processor
data_process.py
from my_package.class_one import ClassOne
run_me.py
from data_processor.data_process import DataProcess
\my_package
class_one.py
Finally, it's not recommended (complexity, cause confusion and difficulty to read the code) but I think you can try to use a 'sys.path' to add the parent directory to the Python path. I think it will allow you to use a relative import:
import sys
sys.path.insert(0, '..')
from class_one import ClassOne
Why you get that error?
Remember relative imports are resolved using __package__ variable(I'm talking about ..class_one). Add a simple print statement in your data_process.py to see the value of this variable:
print(__package__)
You're in Project folder and you run python run_me.py, so this variable must be: 'data_processor'. So you can't go beyond "one" level up. (It follows the dots as we see next).
When you can go one level up?
In run_me.py change your import statement from:
from data_processor.data_process import DataProcess
to
from Project.data_processor.data_process import DataProcess
Before running your script, we need to tell Python where to find Project folder. It doesn't know right now! We are in Project directory and there is no Project directory in where we are. So just add it to the sys.path in run_me.py:
import sys
sys.path.insert(0, PATH TO PARENT OF Project DIRECTORY)
Now run your command -> python run_me.py. Every thing works fine.
Did you notice the value of __package__? It's now 'Project.data_processor'. We went one level down, so we can go one level up .( As I said, it follows the dots.)
That was the reason. But what you can do now?
I think the most simple solution is to just stick with absolute imports. If you know in which directory you are and check the records in sys.path(Add to the paths if necessary), you won't get into problems.
You can manually hack __package__ which I do not recommend. To do so, add:
__package__ = "Project.data_processor"
at the top in your data_process.py file. Then add this to the run_me.py
import sys
sys.path.insert(0, PATH TO PARENT OF Project DIRECTORY)
This way you don't need to change your original import statement. That from data_processor.data_process import DataProcess just works.
For this option, you don't need to hack __package__ nor adding any path to the sys.path. Just change your import statement from:
from data_processor.data_process import DataProcess
to
from Project.data_processor.data_process import DataProcess
But for executing your command, you should go to the parent directory and run your script like:
python -m Project.run_me

Python custom module and import

I am following this example on how to package a python module. But installing my built package with pip, when I tried to use it, while the following works.
from towel_stuff import towel_utils
x = towel_utils.has_towel()
print(x)
And this also works,
import towel_stuff.towel_utils
x = towel_stuff.towel_utils.has_towel()
print(x)
I don't understand, why the following doesn't work.
import towel_stuff
x = towel_stuff.towel_utils.has_towel()
print(x)
Normally, for example if we want to use os.path, we don't need to write import os.path, but just import os is enough. So, with my built package, why do I have to give the full package path?
Of course I can use from towel_stuff import * to import everything, but was just curious why we don't need to give the full path for standard packages.
Given the following structure:
towel_stuff
----__init__.py
----towel_utils
When you use import towel_stuff, the only file executed is __init__.py, so if you haven't imported towel_utils in __init__.py, it is not accessible at all.
So in short, when you use import a_module, you are and only are executing the __init__.py file in that module directory. If you want to access the a_module.file, you need to explicitly import it.
When you use import a_file, you are executing that file, as path is just a variable of os, so you can access it like os.path.
So the difference is, path is a variable in os while towel_utils is a submodule in towel_stuff. Or let's say path is an imported module in os which makes it become a variable.
Normally, for example if we want to use os.path, we don't need to write import os.path, but just import os is enough. So, with my built package, why do I have to give the full package path?
It all depends on how the module is constructed. For example, if in your towel_stuff module you included:
from towel_stuff import towel_utils
Then code that imported only towel_stuff would have access to towel_stuff.towel_utils without additional imports.

Importing from relative path in python syntax error

I am trying to import from relative path in my python program.
the class i would like to import is in
home/foo/bar/model.py
However, my current python script is in
home/best/user/test.py
i have tried to use
from ../../foo/bar import class
But it throws up a syntax error
When importing modules, python looks in the current working directory and in the paths in sys.path. You can add the directory of the script you would like to import to sys.path:
import sys
sys.path.append('home/foo/bar')
import model # imports home/foo/bar/model.py
You can't do that. You can't import from an explicitly specified path (without awful trickery). All Python imports are based on the systemwide import paths (in sys,path). You can't import anything that isn't reachable from sys,path (i.e., it's either on sys.path itself or it's inside a package that's on sys.path). The documenation has the details. If you want to be able to import from that file, you need to somehow add its directory (or the directory of its topmost containing package) to the path.

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