What is the best way to import a module from a path?
python - How can I import a module dynamically given the full path? - Stack Overflow
Python 2.7 - Cannot skip symbolic link despite os.walk(followlinks) and also having a conditional statement to do so
Pip3 install on wsl does not allow python to access modules
So my suggestion is to NEVER use sudo to allow pip to install your rando libraries into the system .
-
Ubuntu relies on python to work, and you risk your system by changing the system configuration
-
Best practice is to install locally using
--user, and even better to install into project specific virtual environments using any of virtualenv, or-m venvor poetry or pyenv. You'll find doing so makes it easier to migrate and recreate your project elsewhere and keeps your various dev activities separated
"[x module] is located in /home/user/.local/bin/
I'm not sure, but it seems as if your module was installed as "--user" and it's not PATH but PYTHONPATH that you probably want to change
More on reddit.comWhat is the best way to import a module from a path?I am writing a script that is supposed to run both on windows and linux machines and the module is on a share.
Currently I do it like this:
import sys
sys.path.append("windows link to the module")
sys.path.append("linux link to the module")
import mymodule
But that is so ugly :/
The best solution would be something that allows me to just use
import mymodule
// edit:
I just found this : http://codumentary.blogspot.com/2014/11/python-tip-of-year-pip-install-editable.html
maybe i can do it like that
Let's have MyClass in module.name module defined at /path/to/file.py. Below is how we import MyClass from this module
For Python 3.5+ use (docs):
import importlib.util
import sys
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = foo
spec.loader.exec_module(foo)
foo.MyClass()
For Python 3.3 and 3.4 use:
from importlib.machinery import SourceFileLoader
foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()
(Although this has been deprecated in Python 3.4.)
For Python 2 use:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
There are equivalent convenience functions for compiled Python files and DLLs.
See also http://bugs.python.org/issue21436.
The advantage of adding a path to sys.path (over using imp) is that it simplifies things when importing more than one module from a single package. For example:
import sys
# the mock-0.3.1 dir contains testcase.py, testutils.py & mock.py
sys.path.append('/foo/bar/mock-0.3.1')
from testcase import TestCase
from testutils import RunTests
from mock import Mock, sentinel, patch