<p>How do I load a Python module given its full path?</p>
<p>Note that the file can be anywhere in the filesystem where the user has access rights.</p>
<hr />
<p><sub><strong>See also:</strong> <a href="https://stackoverflow.com/questions/301134">How to import a module given its name as string?</a></sub></p>

[{'answer_id': 67672, 'author': 'Matt', 'author_id': 10035, 'author_profile': 'https://Stackoverflow.com/users/10035', 'pm_score': 3, 'selected': False, 'text': '<p>I believe you can use <a href="https://docs.python.org/2/library/imp.html#imp.find_module" rel="noreferrer"><code>imp.find_module()</code></a> and <a href="https://docs.python.org/2/library/imp.html#imp.load_module" rel="noreferrer"><code>imp.load_module()</code></a> to load the specified module.  You\'ll need to split the module name off of the path, i.e. if you wanted to load <code>/home/mypath/mymodule.py</code> you\'d need to do:</p>\n\n<pre><code>imp.find_module(\'mymodule\', \'/home/mypath/\')\n</code></pre>\n\n<p>...but that should get the job done.</p>\n'}, {'answer_id': 67692, 'author': 'Sebastian Rittau', 'author_id': 7779, 'author_profile': 'https://Stackoverflow.com/users/7779', 'pm_score': 12, 'selected': True, 'text': '<p>For Python 3.5+ use (<a href="https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly" rel="noreferrer">docs</a>):</p>\n<pre><code>import importlib.util\nimport sys\nspec = importlib.util.spec_from_file_location(&quot;module.name&quot;, &quot;/path/to/file.py&quot;)\nfoo = importlib.util.module_from_spec(spec)\nsys.modules[&quot;module.name&quot;] = foo\nspec.loader.exec_module(foo)\nfoo.MyClass()\n</code></pre>\n<p>For Python 3.3 and 3.4 use:</p>\n<pre><code>from importlib.machinery import SourceFileLoader\n\nfoo = SourceFileLoader(&quot;module.name&quot;, &quot;/path/to/file.py&quot;).load_module()\nfoo.MyClass()\n</code></pre>\n<p>(Although this has been deprecated in Python 3.4.)</p>\n<p>For Python 2 use:</p>\n<pre><code>import imp\n\nfoo = imp.load_source(\'module.name\', \'/path/to/file.py\')\nfoo.MyClass()\n</code></pre>\n<p>There are equivalent convenience functions for compiled Python files and DLLs.</p>\n<p>See also <a href="http://bugs.python.org/issue21436" rel="noreferrer">http://bugs.python.org/issue21436</a>.</p>\n'}, {'answer_id': 67693, 'author': 'zuber', 'author_id': 9812, 'author_profile': 'https://Stackoverflow.com/users/9812', 'pm_score': 4, 'selected': False, 'text': '<p>You can use the</p>\n<pre><code>load_source(module_name, path_to_file)\n</code></pre>\n<p>method from the <a href="https://docs.python.org/library/imp.html" rel="nofollow noreferrer">imp module</a>.</p>\n'}, {'answer_id': 67705, 'author': 'user10370', 'author_id': 10370, 'author_profile': 'https://Stackoverflow.com/users/10370', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Import package modules at runtime (Python recipe)</strong> </p>\n\n<p><a href="http://code.activestate.com/recipes/223972/" rel="nofollow noreferrer">http://code.activestate.com/recipes/223972/</a></p>\n\n<pre><code>###################\n##                #\n## classloader.py #\n##                #\n###################\n\nimport sys, types\n\ndef _get_mod(modulePath):\n    try:\n        aMod = sys.modules[modulePath]\n        if not isinstance(aMod, types.ModuleType):\n            raise KeyError\n    except KeyError:\n        # The last [\'\'] is very important!\n        aMod = __import__(modulePath, globals(), locals(), [\'\'])\n        sys.modules[modulePath] = aMod\n    return aMod\n\ndef _get_func(fullFuncName):\n    """Retrieve a function object from a full dotted-package name."""\n\n    # Parse out the path, module, and function\n    lastDot = fullFuncName.rfind(u".")\n    funcName = fullFuncName[lastDot + 1:]\n    modPath = fullFuncName[:lastDot]\n\n    aMod = _get_mod(modPath)\n    aFunc = getattr(aMod, funcName)\n\n    # Assert that the function is a *callable* attribute.\n    assert callable(aFunc), u"%s is not callable." % fullFuncName\n\n    # Return a reference to the function itself,\n    # not the results of the function.\n    return aFunc\n\ndef _get_class(fullClassName, parentClass=None):\n    """Load a module and retrieve a class (NOT an instance).\n\n    If the parentClass is supplied, className must be of parentClass\n    or a subclass of parentClass (or None is returned).\n    """\n    aClass = _get_func(fullClassName)\n\n    # Assert that the class is a subclass of parentClass.\n    if parentClass is not None:\n        if not issubclass(aClass, parentClass):\n            raise TypeError(u"%s is not a subclass of %s" %\n                            (fullClassName, parentClass))\n\n    # Return a reference to the class itself, not an instantiated object.\n    return aClass\n\n\n######################\n##       Usage      ##\n######################\n\nclass StorageManager: pass\nclass StorageManagerMySQL(StorageManager): pass\n\ndef storage_object(aFullClassName, allOptions={}):\n    aStoreClass = _get_class(aFullClassName, StorageManager)\n    return aStoreClass(allOptions)\n</code></pre>\n'}, {'answer_id': 67708, 'author': 'ctcherry', 'author_id': 10322, 'author_profile': 'https://Stackoverflow.com/users/10322', 'pm_score': 5, 'selected': False, 'text': '<p>You can also do something like this and add the directory that the configuration file is sitting in to the Python load path, and then just do a normal import, assuming you know the name of the file in advance, in this case "config".</p>\n\n<p>Messy, but it works.</p>\n\n<pre><code>configfile = \'~/config.py\'\n\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.expanduser(configfile)))\n\nimport config\n</code></pre>\n'}, {'answer_id': 67715, 'author': 'Wheat', 'author_id': 70142, 'author_profile': 'https://Stackoverflow.com/users/70142', 'pm_score': 4, 'selected': False, 'text': "<p>Do you mean load or import?</p>\n<p>You can manipulate the <code>sys.path</code> list specify the path to your module, and then import your module. For example, given a module at:</p>\n<pre><code>/foo/bar.py\n</code></pre>\n<p>You could do:</p>\n<pre><code>import sys\nsys.path[0:0] = ['/foo'] # Puts the /foo directory at the start of your path\nimport bar\n</code></pre>\n"}, {'answer_id': 68628, 'author': 'Chris Calloway', 'author_id': 10769, 'author_profile': 'https://Stackoverflow.com/users/10769', 'pm_score': 4, 'selected': False, 'text': '<p>You can do this using <code>__import__</code> and <code>chdir</code>:</p>\n<pre class="lang-py prettyprint-override"><code>def import_file(full_path_to_module):\n    try:\n        import os\n        module_dir, module_file = os.path.split(full_path_to_module)\n        module_name, module_ext = os.path.splitext(module_file)\n        save_cwd = os.getcwd()\n        os.chdir(module_dir)\n        module_obj = __import__(module_name)\n        module_obj.__file__ = full_path_to_module\n        globals()[module_name] = module_obj\n        os.chdir(save_cwd)\n    except Exception as e:\n        raise ImportError(e)\n    return module_obj\n\n\nimport_file(\'/home/somebody/somemodule.py\')\n</code></pre>\n'}, {'answer_id': 129374, 'author': 'Daryl Spitzer', 'author_id': 4766, 'author_profile': 'https://Stackoverflow.com/users/4766', 'pm_score': 9, 'selected': False, 'text': "<p>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:</p>\n\n<pre><code>import sys\n# the mock-0.3.1 dir contains testcase.py, testutils.py &amp; mock.py\nsys.path.append('/foo/bar/mock-0.3.1')\n\nfrom testcase import TestCase\nfrom testutils import RunTests\nfrom mock import Mock, sentinel, patch\n</code></pre>\n"}, {'answer_id': 6284270, 'author': 'ubershmekel', 'author_id': 177498, 'author_profile': 'https://Stackoverflow.com/users/177498', 'pm_score': 2, 'selected': False, 'text': '<p>I made a package that uses <code>imp</code> for you. I call it <code>import_file</code> and this is how it\'s used:</p>\n\n<pre><code>&gt;&gt;&gt;from import_file import import_file\n&gt;&gt;&gt;mylib = import_file(\'c:\\\\mylib.py\')\n&gt;&gt;&gt;another = import_file(\'relative_subdir/another.py\')\n</code></pre>\n\n<p>You can get it at:</p>\n\n<p><a href="http://pypi.python.org/pypi/import_file" rel="nofollow">http://pypi.python.org/pypi/import_file</a></p>\n\n<p>or at</p>\n\n<p><a href="http://code.google.com/p/import-file/" rel="nofollow">http://code.google.com/p/import-file/</a></p>\n'}, {'answer_id': 8721254, 'author': 'Hengjie', 'author_id': 914986, 'author_profile': 'https://Stackoverflow.com/users/914986', 'pm_score': 2, 'selected': False, 'text': "<p>This should work</p>\n\n<pre><code>path = os.path.join('./path/to/folder/with/py/files', '*.py')\nfor infile in glob.glob(path):\n    basename = os.path.basename(infile)\n    basename_without_extension = basename[:-3]\n\n    # http://docs.python.org/library/imp.html?highlight=imp#module-imp\n    imp.load_source(basename_without_extension, infile)\n</code></pre>\n"}, {'answer_id': 25827116, 'author': 'bob_twinkles', 'author_id': 783910, 'author_profile': 'https://Stackoverflow.com/users/783910', 'pm_score': 3, 'selected': False, 'text': '<p>You can use the <code>pkgutil</code> module (specifically the <a href="https://docs.python.org/3/library/pkgutil.html#pkgutil.walk_packages" rel="noreferrer"><code>walk_packages</code></a> method) to get a list of the packages in the current directory. From there it\'s trivial to use the <code>importlib</code> machinery to import the modules you want:</p>\n\n<pre><code>import pkgutil\nimport importlib\n\npackages = pkgutil.walk_packages(path=\'.\')\nfor importer, name, is_package in packages:\n    mod = importlib.import_module(name)\n    # do whatever you want with module now, it\'s been imported!\n</code></pre>\n'}, {'answer_id': 26995106, 'author': 'user2760152', 'author_id': 2760152, 'author_profile': 'https://Stackoverflow.com/users/2760152', 'pm_score': 2, 'selected': False, 'text': '<p>In Linux, adding a symbolic link in the directory your Python script is located works.</p>\n<p>I.e.:</p>\n<pre><code>ln -s /absolute/path/to/module/module.py /absolute/path/to/script/module.py\n</code></pre>\n<p>The Python interpreter will create <code>/absolute/path/to/script/module.pyc</code> and will update it if you change the contents of <code>/absolute/path/to/module/module.py</code>.</p>\n<p>Then include the following in file <em>mypythonscript.py</em>:</p>\n<pre><code>from module import *\n</code></pre>\n'}, {'answer_id': 27127448, 'author': 'Zompa', 'author_id': 2783173, 'author_profile': 'https://Stackoverflow.com/users/2783173', 'pm_score': -1, 'selected': False, 'text': '<p>The best way, I think, is from the official documentation (<a href="https://docs.python.org/3.2/library/imp.html#examples" rel="nofollow">29.1. imp — Access the import internals</a>):</p>\n\n<pre><code>import imp\nimport sys\n\ndef __import__(name, globals=None, locals=None, fromlist=None):\n    # Fast path: see if the module has already been imported.\n    try:\n        return sys.modules[name]\n    except KeyError:\n        pass\n\n    # If any of the following calls raises an exception,\n    # there\'s a problem we can\'t handle -- let the caller handle it.\n\n    fp, pathname, description = imp.find_module(name)\n\n    try:\n        return imp.load_module(name, fp, pathname, description)\n    finally:\n        # Since we may exit via an exception, close fp explicitly.\n        if fp:\n            fp.close()\n</code></pre>\n'}, {'answer_id': 29589414, 'author': 'Redlegjed', 'author_id': 4779459, 'author_profile': 'https://Stackoverflow.com/users/4779459', 'pm_score': 3, 'selected': False, 'text': '<p>This area of Python 3.4 seems to be extremely tortuous to understand! However with a bit of hacking using the code from Chris Calloway as a start I managed to get something working. Here\'s the basic function.</p>\n\n<pre><code>def import_module_from_file(full_path_to_module):\n    """\n    Import a module given the full path/filename of the .py file\n\n    Python 3.4\n\n    """\n\n    module = None\n\n    try:\n\n        # Get module name and path from full path\n        module_dir, module_file = os.path.split(full_path_to_module)\n        module_name, module_ext = os.path.splitext(module_file)\n\n        # Get module "spec" from filename\n        spec = importlib.util.spec_from_file_location(module_name,full_path_to_module)\n\n        module = spec.loader.load_module()\n\n    except Exception as ec:\n        # Simple error printing\n        # Insert "sophisticated" stuff here\n        print(ec)\n\n    finally:\n        return module\n</code></pre>\n\n<p>This appears to use non-deprecated modules from Python 3.4. I don\'t pretend to understand why, but it seems to work from within a program. I found Chris\' solution worked on the command line but not from inside a program.</p>\n'}, {'answer_id': 30605451, 'author': 'yoniLavi', 'author_id': 493553, 'author_profile': 'https://Stackoverflow.com/users/493553', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m not saying that it is better, but for the sake of completeness, I wanted to suggest the <a href="https://docs.python.org/3/library/functions.html#exec" rel="nofollow noreferrer"><code>exec</code></a> function, available in both Python\xa02 and Python\xa03.</p>\n<p><code>exec</code> allows you to execute arbitrary code in either the global scope, or in an internal scope, provided as a dictionary.</p>\n<p>For example, if you have a module stored in <code>&quot;/path/to/module</code>&quot; with the function <code>foo()</code>, you could run it by doing the following:</p>\n<pre><code>module = dict()\nwith open(&quot;/path/to/module&quot;) as f:\n    exec(f.read(), module)\nmodule[\'foo\']()\n</code></pre>\n<p>This makes it a bit more explicit that you\'re loading code dynamically, and grants you some additional power, such as the ability to provide custom builtins.</p>\n<p>And if having access through attributes, instead of keys is important to you, you can design a custom dict class for the globals, that provides such access, e.g.:</p>\n<pre><code>class MyModuleClass(dict):\n    def __getattr__(self, name):\n        return self.__getitem__(name)\n</code></pre>\n'}, {'answer_id': 32905959, 'author': 'Peter Zhu', 'author_id': 4388898, 'author_profile': 'https://Stackoverflow.com/users/4388898', 'pm_score': 2, 'selected': False, 'text': '<p>To import a module from a given filename, you can temporarily extend the path, and restore the system path in the finally block <a href="http://effbot.org/zone/import-string.htm" rel="nofollow">reference:</a></p>\n\n<pre><code>filename = "directory/module.py"\n\ndirectory, module_name = os.path.split(filename)\nmodule_name = os.path.splitext(module_name)[0]\n\npath = list(sys.path)\nsys.path.insert(0, directory)\ntry:\n    module = __import__(module_name)\nfinally:\n    sys.path[:] = path # restore\n</code></pre>\n'}, {'answer_id': 37339817, 'author': 'ncoghlan', 'author_id': 597742, 'author_profile': 'https://Stackoverflow.com/users/597742', 'pm_score': 6, 'selected': False, 'text': '<p>It sounds like you don\'t want to specifically import the configuration file (which has a whole lot of side effects and additional complications involved). You just want to run it, and be able to access the resulting namespace. The standard library provides an API specifically for that in the form of <a href="https://docs.python.org/3/library/runpy.html#runpy.run_path" rel="noreferrer">runpy.run_path</a>:</p>\n<pre><code>from runpy import run_path\nsettings = run_path(&quot;/path/to/file.py&quot;)\n</code></pre>\n<p>That interface is available in Python 2.7 and Python 3.2+.</p>\n'}, {'answer_id': 37611448, 'author': 'sorin', 'author_id': 99834, 'author_profile': 'https://Stackoverflow.com/users/99834', 'pm_score': 4, 'selected': False, 'text': "<p>Here is some code that works in all Python versions, from 2.7-3.5 and probably even others.</p>\n<pre><code>config_file = &quot;/tmp/config.py&quot;\nwith open(config_file) as f:\n    code = compile(f.read(), config_file, 'exec')\n    exec(code, globals(), locals())\n</code></pre>\n<p>I tested it. It may be ugly, but so far it is the only one that works in all versions.</p>\n"}, {'answer_id': 43602557, 'author': 'Mad Physicist', 'author_id': 2988730, 'author_profile': 'https://Stackoverflow.com/users/2988730', 'pm_score': 4, 'selected': False, 'text': '<p>I have come up with a slightly modified version of <a href="https://stackoverflow.com/a/67692/2988730">@SebastianRittau\'s wonderful answer</a> (for Python &gt; 3.4 I think), which will allow you to load a file with any extension as a module using <a href="https://docs.python.org/3/library/importlib.html#importlib.util.spec_from_loader" rel="nofollow noreferrer"><code>spec_from_loader</code></a> instead of <a href="https://docs.python.org/3/library/importlib.html#importlib.util.spec_from_file_location" rel="nofollow noreferrer"><code>spec_from_file_location</code></a>:</p>\n<pre><code>from importlib.util import spec_from_loader, module_from_spec\nfrom importlib.machinery import SourceFileLoader \n\nspec = spec_from_loader(&quot;module.name&quot;, SourceFileLoader(&quot;module.name&quot;, &quot;/path/to/file.py&quot;))\nmod = module_from_spec(spec)\nspec.loader.exec_module(mod)\n</code></pre>\n<p>The advantage of encoding the path in an explicit <a href="https://docs.python.org/3/library/importlib.html#importlib.machinery.SourceFileLoader" rel="nofollow noreferrer"><code>SourceFileLoader</code></a> is that the <a href="https://docs.python.org/3/library/importlib.html#module-importlib.machinery" rel="nofollow noreferrer">machinery</a> will not try to figure out the type of the file from the extension. This means that you can load something like a <code>.txt</code> file using this method, but you could not do it with <code>spec_from_file_location</code> without specifying the loader because <code>.txt</code> is not in <a href="https://docs.python.org/3/library/importlib.html#importlib.machinery.SOURCE_SUFFIXES" rel="nofollow noreferrer"><code>importlib.machinery.SOURCE_SUFFIXES</code></a>.</p>\n<p>I\'ve placed an implementation based on this, and <a href="https://stackoverflow.com/a/50395128/2988730">@SamGrondahl\'s useful modification</a> into my utility library, <a href="https://haggis.readthedocs.io/en/stable/" rel="nofollow noreferrer">haggis</a>. The function is called <a href="https://haggis.readthedocs.io/en/latest/api.html#haggis.load.load_module" rel="nofollow noreferrer"><code>haggis.load.load_module</code></a>. It adds a couple of neat tricks, like the ability to inject variables into the module namespace as it is loaded.</p>\n'}, {'answer_id': 48191370, 'author': 'David', 'author_id': 926217, 'author_profile': 'https://Stackoverflow.com/users/926217', 'pm_score': 2, 'selected': False, 'text': "<p>This will allow imports of compiled (pyd) Python modules in 3.4:</p>\n<pre><code>import sys\nimport importlib.machinery\n\ndef load_module(name, filename):\n    # If the Loader finds the module name in this list it will use\n    # module_name.__file__ instead so we need to delete it here\n    if name in sys.modules:\n        del sys.modules[name]\n    loader = importlib.machinery.ExtensionFileLoader(name, filename)\n    module = loader.load_module()\n    locals()[name] = module\n    globals()[name] = module\n\nload_module('something', r'C:\\Path\\To\\something.pyd')\nsomething.do_something()\n</code></pre>\n"}, {'answer_id': 48455971, 'author': 'Andrei Keino', 'author_id': 3859945, 'author_profile': 'https://Stackoverflow.com/users/3859945', 'pm_score': 2, 'selected': False, 'text': "<p>A quite simple way: suppose you want import file with relative path ../../MyLibs/pyfunc.py</p>\n<pre><code>libPath = '../../MyLibs'\nimport sys\nif not libPath in sys.path: sys.path.append(libPath)\nimport pyfunc as pf\n</code></pre>\n<p>But if you make it without a guard you can finally get a very long path.</p>\n"}, {'answer_id': 50395128, 'author': 'Sam Grondahl', 'author_id': 1188448, 'author_profile': 'https://Stackoverflow.com/users/1188448', 'pm_score': 7, 'selected': False, 'text': '<p>If your top-level module is not a file but is packaged as a directory with __init__.py, then the accepted solution almost works, but not quite. In Python 3.5+ the following code is needed (note the added line that begins with \'sys.modules\'):</p>\n\n<pre><code>MODULE_PATH = "/path/to/your/module/__init__.py"\nMODULE_NAME = "mymodule"\nimport importlib\nimport sys\nspec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)\nmodule = importlib.util.module_from_spec(spec)\nsys.modules[spec.name] = module \nspec.loader.exec_module(module)\n</code></pre>\n\n<p>Without this line, when exec_module is executed, it tries to bind relative imports in your top level __init__.py to the top level module name -- in this case "mymodule". But "mymodule" isn\'t loaded yet so you\'ll get the error "SystemError: Parent module \'mymodule\' not loaded, cannot perform relative import". So you need to bind the name before you load it. The reason for this is the fundamental invariant of the relative import system: "The invariant holding is that if you have sys.modules[\'spam\'] and sys.modules[\'spam.foo\'] (as you would after the above import), the latter must appear as the foo attribute of the former" <a href="https://docs.python.org/3/reference/import.html#submodules" rel="noreferrer">as discussed here</a>.</p>\n'}, {'answer_id': 50509034, 'author': 'Ataxias', 'author_id': 4055338, 'author_profile': 'https://Stackoverflow.com/users/4055338', 'pm_score': 2, 'selected': False, 'text': '<p>A simple solution using <code>importlib</code> instead of the <code>imp</code> package (tested for Python 2.7, although it should work for Python 3 too):</p>\n\n<pre class="lang-python prettyprint-override"><code>import importlib\n\ndirname, basename = os.path.split(pyfilepath) # pyfilepath: \'/my/path/mymodule.py\'\nsys.path.append(dirname) # only directories should be added to PYTHONPATH\nmodule_name = os.path.splitext(basename)[0] # \'/my/path/mymodule.py\' --&gt; \'mymodule\'\nmodule = importlib.import_module(module_name) # name space of defined module (otherwise we would literally look for "module_name")\n</code></pre>\n\n<p>Now you can directly use the namespace of the imported module, like this:</p>\n\n<pre><code>a = module.myvar\nb = module.myfunc(a)\n</code></pre>\n\n<p>The advantage of this solution is that <strong>we don\'t even need to know the actual name of the module we would like to import</strong>, in order to use it in our code. This is useful, e.g. in case the path of the module is a configurable argument.</p>\n'}, {'answer_id': 52236722, 'author': 'Michael Scott Asato Cuthbert', 'author_id': 1293501, 'author_profile': 'https://Stackoverflow.com/users/1293501', 'pm_score': 0, 'selected': False, 'text': '<p>This answer is a supplement to <a href="https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path/67692#67692">Sebastian Rittau\'s answer</a> responding to the comment: &quot;but what if you don\'t have the module name?&quot;  This is a quick and dirty way of getting the likely Python module name given a filename -- it just goes up the tree until it finds a directory without an <code>__init__.py</code> file and then turns it back into a filename.  For Python 3.4+ (uses pathlib), which makes sense since Python\xa02 people can use &quot;imp&quot; or other ways of doing relative imports:</p>\n<pre><code>import pathlib\n\ndef likely_python_module(filename):\n    \'\'\'\n    Given a filename or Path, return the &quot;likely&quot; python module name.  That is, iterate\n    the parent directories until it doesn\'t contain an __init__.py file.\n\n    :rtype: str\n    \'\'\'\n    p = pathlib.Path(filename).resolve()\n    paths = []\n    if p.name != \'__init__.py\':\n        paths.append(p.stem)\n    while True:\n        p = p.parent\n        if not p:\n            break\n        if not p.is_dir():\n            break\n\n        inits = [f for f in p.iterdir() if f.name == \'__init__.py\']\n        if not inits:\n            break\n\n        paths.append(p.stem)\n\n    return \'.\'.join(reversed(paths))\n</code></pre>\n<p>There are certainly possibilities for improvement, and the optional <code>__init__.py</code> files might necessitate other changes, but if you have <code>__init__.py</code> in general, this does the trick.</p>\n'}, {'answer_id': 53311583, 'author': 'Miladiouss', 'author_id': 7428659, 'author_profile': 'https://Stackoverflow.com/users/7428659', 'pm_score': 7, 'selected': False, 'text': '<p>To import your module, you need to add its directory to the environment variable, either temporarily or permanently.</p>\n<h1>Temporarily</h1>\n<pre><code>import sys\nsys.path.append(&quot;/path/to/my/modules/&quot;)\nimport my_module\n</code></pre>\n<h1>Permanently</h1>\n<p>Adding the following line to your <code>.bashrc</code> (or alternative) file in Linux\nand excecute <code>source ~/.bashrc</code> (or alternative) in the terminal:</p>\n<pre><code>export PYTHONPATH=&quot;${PYTHONPATH}:/path/to/my/modules/&quot;\n</code></pre>\n<p>Credit/Source: <a href="https://stackoverflow.com/users/2312075/saarrrr">saarrrr</a>, <a href="https://stackoverflow.com/a/3402176/7428659">another Stack\xa0Exchange question</a></p>\n'}, {'answer_id': 53651717, 'author': 'abhimanyu', 'author_id': 8135029, 'author_profile': 'https://Stackoverflow.com/users/8135029', 'pm_score': 3, 'selected': False, 'text': '<p>Create Python module <em>test.py</em>:</p>\n<pre><code>import sys\nsys.path.append(&quot;&lt;project-path&gt;/lib/&quot;)\nfrom tes1 import Client1\nfrom tes2 import Client2\nimport tes3\n</code></pre>\n<p>Create Python module <em>test_check.py</em>:</p>\n<pre><code>from test import Client1\nfrom test import Client2\nfrom test import test3\n</code></pre>\n<p>We can import the imported module from module.</p>\n'}, {'answer_id': 57843421, 'author': 'Andry', 'author_id': 2672125, 'author_profile': 'https://Stackoverflow.com/users/2672125', 'pm_score': 2, 'selected': False, 'text': '<p>I have written my own global and portable import function, based on <code>importlib</code> module, for:</p>\n<ul>\n<li>Be able to import both modules as submodules and to import the content of a module to a parent module (or into a globals if has no parent module).</li>\n<li>Be able to import modules with a period characters in a file name.</li>\n<li>Be able to import modules with any extension.</li>\n<li>Be able to use a standalone name for a submodule instead of a file name without extension which is by default.</li>\n<li>Be able to define the import order based on previously imported module instead of dependent on <code>sys.path</code> or on a what ever search path storage.</li>\n</ul>\n<p>The examples directory structure:</p>\n<pre><code>&lt;root&gt;\n |\n +- test.py\n |\n +- testlib.py\n |\n +- /std1\n |   |\n |   +- testlib.std1.py\n |\n +- /std2\n |   |\n |   +- testlib.std2.py\n |\n +- /std3\n     |\n     +- testlib.std3.py\n</code></pre>\n<p>Inclusion dependency and order:</p>\n<pre><code>test.py\n  -&gt; testlib.py\n    -&gt; testlib.std1.py\n      -&gt; testlib.std2.py\n    -&gt; testlib.std3.py\n</code></pre>\n<p>Implementation:</p>\n<p>Latest changes store: <a href="https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/python/tacklelib/tacklelib.py" rel="nofollow noreferrer">https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/python/tacklelib/tacklelib.py</a></p>\n<p><strong>test.py</strong>:</p>\n<pre><code>import os, sys, inspect, copy\n\nSOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace(\'\\\\\',\'/\')\nSOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;test::SOURCE_FILE: &quot;, SOURCE_FILE)\n\n# portable import to the global space\nsys.path.append(TACKLELIB_ROOT) # TACKLELIB_ROOT - path to the library directory\nimport tacklelib as tkl\n\ntkl.tkl_init(tkl)\n\n# cleanup\ndel tkl # must be instead of `tkl = None`, otherwise the variable would be still persist\nsys.path.pop()\n\ntkl_import_module(SOURCE_DIR, \'testlib.py\')\n\nprint(globals().keys())\n\ntestlib.base_test()\ntestlib.testlib_std1.std1_test()\ntestlib.testlib_std1.testlib_std2.std2_test()\n#testlib.testlib.std3.std3_test()                             # does not reachable directly ...\ngetattr(globals()[\'testlib\'], \'testlib.std3\').std3_test()     # ... but reachable through the `globals` + `getattr`\n\ntkl_import_module(SOURCE_DIR, \'testlib.py\', \'.\')\n\nprint(globals().keys())\n\nbase_test()\ntestlib_std1.std1_test()\ntestlib_std1.testlib_std2.std2_test()\n#testlib.std3.std3_test()                                     # does not reachable directly ...\nglobals()[\'testlib.std3\'].std3_test()                         # ... but reachable through the `globals` + `getattr`\n</code></pre>\n<p><strong>testlib.py</strong>:</p>\n<pre><code># optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace(\'\\\\\',\'/\')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;1 testlib::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + \'/std1\', \'testlib.std1.py\', \'testlib_std1\')\n\n# SOURCE_DIR is restored here\nprint(&quot;2 testlib::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + \'/std3\', \'testlib.std3.py\')\n\nprint(&quot;3 testlib::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ndef base_test():\n  print(\'base_test\')\n</code></pre>\n<p><strong>testlib.std1.py</strong>:</p>\n<pre><code># optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace(\'\\\\\',\'/\')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;testlib.std1::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ntkl_import_module(SOURCE_DIR + \'/../std2\', \'testlib.std2.py\', \'testlib_std2\')\n\ndef std1_test():\n  print(\'std1_test\')\n</code></pre>\n<p><strong>testlib.std2.py</strong>:</p>\n<pre><code># optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace(\'\\\\\',\'/\')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;testlib.std2::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ndef std2_test():\n  print(\'std2_test\')\n</code></pre>\n<p><strong>testlib.std3.py</strong>:</p>\n<pre><code># optional for 3.4.x and higher\n#import os, inspect\n#\n#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace(\'\\\\\',\'/\')\n#SOURCE_DIR = os.path.dirname(SOURCE_FILE)\n\nprint(&quot;testlib.std3::SOURCE_FILE: &quot;, SOURCE_FILE)\n\ndef std3_test():\n  print(\'std3_test\')\n</code></pre>\n<p><strong>Output</strong> (<code>3.7.4</code>):</p>\n<pre><code>test::SOURCE_FILE:  &lt;root&gt;/test01/test.py\nimport : &lt;root&gt;/test01/testlib.py as testlib -&gt; []\n1 testlib::SOURCE_FILE:  &lt;root&gt;/test01/testlib.py\nimport : &lt;root&gt;/test01/std1/testlib.std1.py as testlib_std1 -&gt; [\'testlib\']\nimport : &lt;root&gt;/test01/std1/../std2/testlib.std2.py as testlib_std2 -&gt; [\'testlib\', \'testlib_std1\']\ntestlib.std2::SOURCE_FILE:  &lt;root&gt;/test01/std1/../std2/testlib.std2.py\n2 testlib::SOURCE_FILE:  &lt;root&gt;/test01/testlib.py\nimport : &lt;root&gt;/test01/std3/testlib.std3.py as testlib.std3 -&gt; [\'testlib\']\ntestlib.std3::SOURCE_FILE:  &lt;root&gt;/test01/std3/testlib.std3.py\n3 testlib::SOURCE_FILE:  &lt;root&gt;/test01/testlib.py\ndict_keys([\'__name__\', \'__doc__\', \'__package__\', \'__loader__\', \'__spec__\', \'__annotations__\', \'__builtins__\', \'__file__\', \'__cached__\', \'os\', \'sys\', \'inspect\', \'copy\', \'SOURCE_FILE\', \'SOURCE_DIR\', \'TackleGlobalImportModuleState\', \'tkl_membercopy\', \'tkl_merge_module\', \'tkl_get_parent_imported_module_state\', \'tkl_declare_global\', \'tkl_import_module\', \'TackleSourceModuleState\', \'tkl_source_module\', \'TackleLocalImportModuleState\', \'testlib\'])\nbase_test\nstd1_test\nstd2_test\nstd3_test\nimport : &lt;root&gt;/test01/testlib.py as . -&gt; []\n1 testlib::SOURCE_FILE:  &lt;root&gt;/test01/testlib.py\nimport : &lt;root&gt;/test01/std1/testlib.std1.py as testlib_std1 -&gt; [\'testlib\']\nimport : &lt;root&gt;/test01/std1/../std2/testlib.std2.py as testlib_std2 -&gt; [\'testlib\', \'testlib_std1\']\ntestlib.std2::SOURCE_FILE:  &lt;root&gt;/test01/std1/../std2/testlib.std2.py\n2 testlib::SOURCE_FILE:  &lt;root&gt;/test01/testlib.py\nimport : &lt;root&gt;/test01/std3/testlib.std3.py as testlib.std3 -&gt; [\'testlib\']\ntestlib.std3::SOURCE_FILE:  &lt;root&gt;/test01/std3/testlib.std3.py\n3 testlib::SOURCE_FILE:  &lt;root&gt;/test01/testlib.py\ndict_keys([\'__name__\', \'__doc__\', \'__package__\', \'__loader__\', \'__spec__\', \'__annotations__\', \'__builtins__\', \'__file__\', \'__cached__\', \'os\', \'sys\', \'inspect\', \'copy\', \'SOURCE_FILE\', \'SOURCE_DIR\', \'TackleGlobalImportModuleState\', \'tkl_membercopy\', \'tkl_merge_module\', \'tkl_get_parent_imported_module_state\', \'tkl_declare_global\', \'tkl_import_module\', \'TackleSourceModuleState\', \'tkl_source_module\', \'TackleLocalImportModuleState\', \'testlib\', \'testlib_std1\', \'testlib.std3\', \'base_test\'])\nbase_test\nstd1_test\nstd2_test\nstd3_test\n</code></pre>\n<p>Tested in Python <code>3.7.4</code>, <code>3.2.5</code>, <code>2.7.16</code></p>\n<p><strong>Pros</strong>:</p>\n<ul>\n<li>Can import both module as a submodule and can import content of a module to a parent module (or into a globals if has no parent module).</li>\n<li>Can import modules with periods in a file name.</li>\n<li>Can import any extension module from any extension module.</li>\n<li>Can use a standalone name for a submodule instead of a file name without extension which is by default (for example, <code>testlib.std.py</code> as <code>testlib</code>, <code>testlib.blabla.py</code> as <code>testlib_blabla</code> and so on).</li>\n<li>Does not depend on a <code>sys.path</code> or on a what ever search path storage.</li>\n<li>Does not require to save/restore global variables like <code>SOURCE_FILE</code> and <code>SOURCE_DIR</code> between calls to <code>tkl_import_module</code>.</li>\n<li>[for <code>3.4.x</code> and higher] Can mix the module namespaces in nested <code>tkl_import_module</code> calls (ex: <code>named-&gt;local-&gt;named</code> or <code>local-&gt;named-&gt;local</code> and so on).</li>\n<li>[for <code>3.4.x</code> and higher] Can auto export global variables/functions/classes from where being declared to all children modules imported through the <code>tkl_import_module</code> (through the <code>tkl_declare_global</code> function).</li>\n</ul>\n<p><strong>Cons</strong>:</p>\n<ul>\n<li>Does not support complete import:\n<ul>\n<li>Ignores enumerations and subclasses.</li>\n<li>Ignores builtins because each what type has to be copied exclusively.</li>\n<li>Ignore not trivially copiable classes.</li>\n<li>Avoids copying builtin modules including all packaged modules.</li>\n</ul>\n</li>\n<li>[for <code>3.3.x</code> and lower] Require to declare <code>tkl_import_module</code> in all modules which calls to <code>tkl_import_module</code> (code duplication)</li>\n</ul>\n<p><strong>Update 1,2</strong> (for <code>3.4.x</code> and higher only):</p>\n<p>In Python 3.4 and higher you can bypass the requirement to declare <code>tkl_import_module</code> in each module by declare <code>tkl_import_module</code> in a top level module and the function would inject itself to all children modules in a single call (it\'s a kind of self deploy import).</p>\n<p><strong>Update 3</strong>:</p>\n<p>Added function <code>tkl_source_module</code> as analog to bash <code>source</code> with support execution guard upon import (implemented through the module merge instead of import).</p>\n<p><strong>Update 4</strong>:</p>\n<p>Added function <code>tkl_declare_global</code> to auto export a module global variable to all children modules where a module global variable is not visible because is not a part of a child module.</p>\n<p><strong>Update 5</strong>:</p>\n<p>All functions has moved into the tacklelib library, see the link above.</p>\n'}, {'answer_id': 58943466, 'author': 'fny', 'author_id': 390897, 'author_profile': 'https://Stackoverflow.com/users/390897', 'pm_score': 3, 'selected': False, 'text': '<p>There\'s a <a href="https://pypi.org/project/thesmuggler/" rel="noreferrer">package</a> that\'s dedicated to this specifically:</p>\n\n<pre><code>from thesmuggler import smuggle\n\n# À la `import weapons`\nweapons = smuggle(\'weapons.py\')\n\n# À la `from contraband import drugs, alcohol`\ndrugs, alcohol = smuggle(\'drugs\', \'alcohol\', source=\'contraband.py\')\n\n# À la `from contraband import drugs as dope, alcohol as booze`\ndope, booze = smuggle(\'drugs\', \'alcohol\', source=\'contraband.py\')\n</code></pre>\n\n<p>It\'s tested across Python versions (Jython and PyPy too), but it might be overkill depending on the size of your project.</p>\n'}, {'answer_id': 58974141, 'author': 'Kumar KS', 'author_id': 4270698, 'author_profile': 'https://Stackoverflow.com/users/4270698', 'pm_score': 4, 'selected': False, 'text': "<p>If we have scripts in the same project but in different directory means, we can solve this problem by the following method.</p>\n\n<p>In this situation <code>utils.py</code> is in <code>src/main/util/</code></p>\n\n<pre><code>import sys\nsys.path.append('./')\n\nimport src.main.util.utils\n#or\nfrom src.main.util.utils import json_converter # json_converter is example method\n</code></pre>\n"}, {'answer_id': 63332270, 'author': 'Benos', 'author_id': 2321965, 'author_profile': 'https://Stackoverflow.com/users/2321965', 'pm_score': 1, 'selected': False, 'text': '<p>These are my two utility functions using only pathlib. It infers the module name from the path.</p>\n<p>By default, it recursively loads all Python files from folders and replaces <strong>init</strong>.py by the parent folder name. But you can also give a Path and/or a glob to select some specific files.</p>\n<pre><code>from pathlib import Path\nfrom importlib.util import spec_from_file_location, module_from_spec\nfrom typing import Optional\n\n\ndef get_module_from_path(path: Path, relative_to: Optional[Path] = None):\n    if not relative_to:\n        relative_to = Path.cwd()\n\n    abs_path = path.absolute()\n    relative_path = abs_path.relative_to(relative_to.absolute())\n    if relative_path.name == &quot;__init__.py&quot;:\n        relative_path = relative_path.parent\n    module_name = &quot;.&quot;.join(relative_path.with_suffix(&quot;&quot;).parts)\n    mod = module_from_spec(spec_from_file_location(module_name, path))\n    return mod\n\n\ndef get_modules_from_folder(folder: Optional[Path] = None, glob_str: str = &quot;*/**/*.py&quot;):\n    if not folder:\n        folder = Path(&quot;.&quot;)\n\n    mod_list = []\n    for file_path in sorted(folder.glob(glob_str)):\n        mod_list.append(get_module_from_path(file_path))\n\n    return mod_list\n</code></pre>\n'}, {'answer_id': 66181002, 'author': 'Bryan Grace', 'author_id': 2600905, 'author_profile': 'https://Stackoverflow.com/users/2600905', 'pm_score': 0, 'selected': False, 'text': "<p>Here's a way of loading files sort of like C, etc.</p>\n<pre><code>from importlib.machinery import SourceFileLoader\nimport os\n\ndef LOAD(MODULE_PATH):\n    if (MODULE_PATH[0] == &quot;/&quot;):\n        FULL_PATH = MODULE_PATH;\n    else:\n        DIR_PATH = os.path.dirname (os.path.realpath (__file__))\n        FULL_PATH = os.path.normpath (DIR_PATH + &quot;/&quot; + MODULE_PATH)\n\n    return SourceFileLoader (FULL_PATH, FULL_PATH).load_module ()\n</code></pre>\n<p>Implementations where:</p>\n<pre><code>Y = LOAD(&quot;../Z.py&quot;)\nA = LOAD(&quot;./A.py&quot;)\nD = LOAD(&quot;./C/D.py&quot;)\nA_ = LOAD(&quot;/IMPORTS/A.py&quot;)\n\nY.DEF();\nA.DEF();\nD.DEF();\nA_.DEF();\n</code></pre>\n<p>Where each of the files looks like this:</p>\n<pre><code>def DEF():\n    print(&quot;A&quot;);\n</code></pre>\n"}, {'answer_id': 66499112, 'author': 'Mhadhbi issam', 'author_id': 9791039, 'author_profile': 'https://Stackoverflow.com/users/9791039', 'pm_score': -1, 'selected': False, 'text': "<p>I find this is a simple answer:</p>\n<pre><code>module = dict()\n\ncode = &quot;&quot;&quot;\nimport json\n\ndef testhi() :\n    return json.dumps({&quot;key&quot; : &quot;value&quot;}, indent = 4 )\n&quot;&quot;&quot;\n\nexec(code, module)\nx = module['testhi']()\nprint(x)\n</code></pre>\n"}, {'answer_id': 68361215, 'author': 'ジョージ', 'author_id': 558008, 'author_profile': 'https://Stackoverflow.com/users/558008', 'pm_score': 3, 'selected': False, 'text': '<p>To add to <a href="https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path/67692#67692">Sebastian Rittau</a>\'s answer:\nAt least for <a href="https://en.wikipedia.org/wiki/CPython" rel="noreferrer">CPython</a>, there\'s <a href="https://docs.python.org/3/library/pydoc.html" rel="noreferrer">pydoc</a>, and, while not officially declared, importing files is what it does:</p>\n<pre class="lang-py prettyprint-override"><code>from pydoc import importfile\nmodule = importfile(\'/path/to/module.py\')\n</code></pre>\n<p><strong>PS.</strong> For the sake of completeness, there\'s a reference to the current implementation at the moment of writing: <a href="https://github.com/python/cpython/blob/9c3eaf88dc5d5bed80cc45936de06b7b3162bc6d/Lib/pydoc.py#L392" rel="noreferrer">pydoc.py</a>, and I\'m pleased to say that in the vein of <a href="https://xkcd.com/1987/" rel="noreferrer">xkcd 1987</a> it uses neither of the implementations mentioned in <a href="https://bugs.python.org/issue21436" rel="noreferrer">issue 21436</a> -- at least, not verbatim.</p>\n'}, {'answer_id': 69286913, 'author': 'Max Kleiner', 'author_id': 9041224, 'author_profile': 'https://Stackoverflow.com/users/9041224', 'pm_score': -1, 'selected': False, 'text': "<p>Something special is to import a module with absolute path with Exec():\n(exec takes a code string or code object. While eval takes an expression.)</p>\n<pre><code>PYMODULE = 'C:\\maXbox\\mX47464\\maxbox4\\examples\\histogram15.py';\nExecstring(LoadStringJ(PYMODULE));\n</code></pre>\n<p>And then get values or object with eval():</p>\n<pre><code>println('get module data: '+evalStr('pyplot.hist(x)'));\n</code></pre>\n<p>Load a module with exec is like an import with wildcard namespace:</p>\n<pre><code>Execstring('sys.path.append(r'+'&quot;'+PYMODULEPATH+'&quot;)');\nExecstring('from histogram import *'); \n</code></pre>\n"}, {'answer_id': 70797815, 'author': 'Jorge', 'author_id': 3170848, 'author_profile': 'https://Stackoverflow.com/users/3170848', 'pm_score': 0, 'selected': False, 'text': "<p>You can use importfile from pydoc</p>\n<pre><code>from pydoc import importfile\nmodule = importfile('/full/path/to/module/module.py')\nname = module.myclass() # myclass is a class inside your python file\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/67631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10286/']