I have a file called foobar (without .py extension). In the same directory I have another python file that tries to import it:
import foobar
But this only works if I rename the file to foobar.py. Is it possible to import a python module that doesn't have the .py extension?
Update: the file has no extension because I also use it as a standalone script, and I don't want to type the .py extension to run it.
Update2: I will go for the symlink solution mentioned below.
py extension is unnecessary for running the script. You only have to make the script executable (e.g. by running chmod a+x script ) and add the shebang line ( #!/usr/bin/env python ).
This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files. Example : Python3.
The Files with the . py extension contain the Python source code. The Python language has become very famous language now a days. It can be used for system scripting, web and software development and mathematics.
You can use the imp.load_source
function (from the imp
module), to load a module dynamically from a given file-system path.
import imp foobar = imp.load_source('foobar', '/path/to/foobar')
This SO discussion also shows some interesting options.
Here is a solution for Python 3.4+:
from importlib.util import spec_from_loader, module_from_spec from importlib.machinery import SourceFileLoader spec = spec_from_loader("foobar", SourceFileLoader("foobar", "/path/to/foobar")) foobar = module_from_spec(spec) spec.loader.exec_module(foobar)
Using spec_from_loader
and explicitly specifying a SourceFileLoader
will force the machinery to load the file as source, without trying to figure out the type of the file from the extension. This means that you can load the file even though it is not listed in importlib.machinery.SOURCE_SUFFIXES
.
If you want to keep importing the file by name after the first load, add the module to sys.modules
:
sys.modules['foobar'] = foobar
You can find an implementation of this function in a utility library I maintain called haggis. haggis.load.load_module
has options for adding the module to sys.modules
, setting a custom name, and injecting variables into the namespace for the code to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With