Importing a module without creating a .pyc/.pyo file?

David Bolen db3l at fitlinxx.com
Fri Jan 25 16:04:17 EST 2002


Michael Hudson <mwh at python.net> writes:

> Like Alex said, you could use imp, or you could just do it by hand
> 
> newm = new.module(name)
> sys.modules[name] = newm
> newm.__file__ = filepath
> exec compile(open(filepath).read(), filepath, "exec") in \
>         newm.__dict__
> 
> comes fairly close, I think.

Note that there's a difference in compile()ing a file versus importing
it in the way a lack of final line ending is handled in the file by
the low level parser.  Importing will add it if necessary, while
compile() won't, and if you don't have it it can lead to SyntaxError
exceptions.  So I'd suggest adding a +'\n' to the output of read()
before passing it on to compile() to really behave the same.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list