Import module with non-standard file name

Simon Forman rogue_pedro at yahoo.com
Tue Aug 8 01:18:14 EDT 2006


Ben Finney wrote:
> Howdy all,
>
> Question: I have Python modules named without '.py' as the extension,
> and I'd like to be able to import them. How can I do that?
>
> Background:
>
> On Unix, I write programs intended to be run as commands to a file
> with no extension. This allows other programs to use the command as an
> interface, and I can re-write the program in some other language
> without obsoleting the commandline interface.
>
> e.g., I might write 'frobnicate-foo' as a shell program so that other
> programs can 'frobnicate-foo --bar baz'. If I later decide to
> re-implement 'frobnicate-foo' in Python, I'll save the top level
> module to the same file name since it implements the same command-line
> interface.
>
> Now that I've got it written as a Python module, I'd like to write
> unit tests for that module, which of course will need to import the
> program module to test it. The unit test can explicitly add the
> directory where the program module lives to 'sys.path' for the purpose
> of importing that module.
>
> However, the Python reference tells me that 'import' (specifically,
> '__import__()') needs modules to live in files named a particular way:
> with a '.py' suffix. But my module is in a file called
> 'frobnicate-foo', with no suffix, and that's part of the definition of
> the program interface.
>
> I don't want symbolic links, or anything else that presents two
> filenames for the same module, because there's no need for that except
> for Python's apparent insistence on a particular naming
> convention. Also, avoiding symbolic links inside the source code tree
> makes version control smoother.
>
>
> What are my options to import a module from a file whose name can't
> change?
>
> --
>  \     "[W]e are still the first generation of users, and for all that |
>   `\     we may have invented the net, we still don't really get it."  |
> _o__)                                                 -- Douglas Adams |
> Ben Finney

Leave your python module with the .py extension and create a small
python script without the .py extension to import and run your code
from the command line.

For example, on my [linux] system /usr/local/bin/idle contains this:

#!/usr/bin/python

from idlelib.PyShell import main
if __name__ == '__main__':
    main()

You also get a modest performance boost because the interpreter will
only process the text of this small script but will use the precompiled
byte-code .pyc files (when available) of your main module, rather than
re-parsing its text.

HTH,
~Simon




More information about the Python-list mailing list