Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a python module without the .py extension

Tags:

python

import

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.

like image 585
compie Avatar asked Apr 08 '10 15:04

compie


People also ask

How do I run a Python file without py extension?

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 ).

Can you manually import a module in 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.

What is a .py extension?

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.


2 Answers

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.

like image 180
Eli Bendersky Avatar answered Sep 19 '22 18:09

Eli Bendersky


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.

like image 31
Mad Physicist Avatar answered Sep 21 '22 18:09

Mad Physicist