Importing files other than *.py

Carlos Ribeiro carribeiro at gmail.com
Fri Nov 19 01:21:40 CET 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?

Hi Ed,

I've been working on a 'dynamic code loader' that does something
similar. I wanted to have a repository of classes that could be
dynamically updated without stopping the application server. I tried
to understand Python import internals (boldly posting some questions
at python-dev) but in the end, I realized that it would be way too
confusing. My advice: don't try it :-) I ended up doing something
simpler, but still had to hack my way.

The solution is to use the execfile() builtin. It takes any file name
(with any extension) as an argument. The catch (that costed me a
couple of hours) is that you need to provide it with a suitable
environment to run, if you want to retrieve the results in a sane &
safe way.

execfile() takes two optional parameters: one is for the globals() and
the other one for the locals() environment. Simple dicts can be
supplied, and wil be looked at for attribute access & storage, pretty
much like for any code executing in Python. For my purposes, I ended
up using only one. You can provide pre-initialized references in this
dict; it's safer than passing the full globals() environment. For
example:

    myglobals = { 'myobj': myobj }
    execfile('arbitraryfile.xyz', myglobals)

... and your code at 'arbitraryfile.xyz' can safely access the 'myobj'
variable. Upon return, any locals symbols that were defined by your
code will also be available on the myglobals dict. As you have passed
a restricted dict for it to work, you have to explicitly copy the
newly defined symbols into your locals() dict.

However, there is a problem with 'import' from within the code being
executed; it will look for modules on the directory where the source
file is located. Thus, if your code tries to import a library from
your system, it may not find it (even if it was located in the same
directory where the code that called it via execfile() was). So,
*before* you call the code, update the sys.path to include any
directories from where you may need to import stuff.

(btw, I've been checking Dabo from time to time. Good to know you're
making progress!).

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list