importing out of cwd

Fredrik Lundh effbot at telia.com
Sun Sep 10 04:31:02 EDT 2000


Alex Martelli wrote:
> You do have to temporarily add to sys.path the directory you want,
> before importing; then, you can take it off again.  This should work:
> 
>     import sys
>     sys.path = [".."] + sys.path
>     import whatever
>     sys.path = sys.path[1:]

insert and pop (or del) is slightly more efficient.

more importantly, it's a good idea to wrap the import
inside a try/finally clause, so you don't screw up the
path if things go wrong:

    sys.path.insert(0, "..")
    try:
        import whatever
    finally:
        sys.path.pop(0)

</F>

<!-- daily news from the python universe:
http://www.pythonware.com/daily/index.htm
-->




More information about the Python-list mailing list