Import module with non-standard file name

John McMonagle jmcmonagle at velseis.com.au
Mon Aug 7 23:00:16 EDT 2006


On Tue, 2006-08-08 at 11:06 +1000, 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?

Why don't you just create a link to the appropriate script ?

For example, 

[me at localhost ~]$ ln -s frobnicate-foo.py frobnicate-foo
[me at localhost ~]$ ll frobnicate*
lrwxrwxrwx  1 me mygroup 17 Aug  8 12:56 frobnicate-foo ->
frobnicate-foo.py*
-rwxr-xr-x  1 me mygroup  0 Aug  8 12:55 frobnicate-foo.py*
-rwxr-xr-x  1 me mygroup  0 Aug  8 12:55 frobnicate-foo.sh*
[me at localhost ~]$

That way you can keep the bash shell script and the python script
independent of one another and you can still import for your unit
testing without any trickery.

Regards,

John




-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.




More information about the Python-list mailing list