Importing files other than *.py
Denis S. Otkidach
ods at strana.ru
Fri Nov 19 05:10:42 EST 2004
On Thu, 18 Nov 2004 19:02:06 -0500
Ed Leafe <ed at leafe.com> wrote:
> If I have a Python script in a file named "burp.zz", is there
> any way
> to import it into another script as you can with files named with the
> .py extension?
>
> I looked at the imp module, but was not able to make it do what
> I
> wanted. Is this possible, or is the py/pyc extension required?
Yes, it's possible:
$ cat > burp.zz <<EOF
> def f():
> print 'OK'
> EOF
$ python
Python 2.4b1 (#1, Oct 29 2004, 15:00:34)
[GCC 3.3.3 20040412 (ALT Linux, build 3.3.3-alt5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> fp = open('burp.zz', 'U')
>>> import imp
>>> module = imp.load_module('burp', fp, 'burp.zz', ('.py', 'U', 1))
>>> module
<module 'burp' from 'burp.zz'>
>>> module.f
<function f at 0x307a04>
>>> module.f()
OK
Alternatively you can use sys.path_hooks to install own importer being
aware of your extentions.
--
Denis S. Otkidach
http://www.python.ru/ [ru]
More information about the Python-list
mailing list