0 votes
1 view
in Python by (47.8k points)

How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.

1 Answer

0 votes
by (107k points)

 

To load the file in Python 3.5 you can run the following code:-

import importlib.util 

spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") 

foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) 

foo.MyClass()

For Python 3.3 and 3.4 use the following piece of code:-

from importlib.machinery import SourceFileLoader 

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module() 

foo.MyClass()

If you are Python 2 user you can run the following code:-:

import imp 

foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass()

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 1, 2019 in Python by Sammy (47.8k points)
+2 votes
3 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...