how to include a file -- not import??

Stefan Schwarzer s.schwarzer at ndh.net
Thu Jan 6 11:43:53 EST 2000


Hello,

Andrew Csillag schrieb:
> The way to make it so that the other code can access variables in the
> including files namespace is:
> exec open('filename').read()

If I understand would you mean :-) that would probably not have the
desired effect if called in a function. In this case the symbols
from the "imported" file would go into the calling function's
namespace and got inaccessible when the function is finished.

For a case when I wanted to execute a file in a specific namespace
I used

# This function allows to customize the always read HTML format from
# html_format.py .
def custom_format( format_file ):
    try:
        execfile( format_file, text_areas.html_format.__dict__ )
    except IOError, msg:
        printerr( 'Warning: can\'t use format file ' + format_file + '\n' )
    except:
        printerr( 'Error: invalid custom format file ' + format_file + '\n' )
        sys.exit( 1 )

This causes the loaded stuff to become visible in
text_areas.html_format . (I'm not sure whether this is entirely
safe, since I only _hope_ to have understood the documentation on
execfile correctly *g*.)

Stefan



More information about the Python-list mailing list