How to - import code not in current directory

Claudio Grondi claudio.grondi at freenet.de
Thu Nov 17 09:37:27 EST 2005


This question seems to come up in this newsgroup quite often, so looking
through past threads will sure provide more details.

Here from "Re: how to import a module from a arbitraty path?"
  posted to comp.lang.python by Simon Brunning on May 26, 2005 09:20 :

"
> I have a program which is going to dynamicly load components from some
> arbitrary defined paths. How to do that?

You can locate them with os.walk and fnmatch. Then you can temporarily
add the directory to sys.path, and import using __import__().
"

so this should work in your case:

import sys
sys.path.append("C:\some\other\directory")
import bar

Claudio


"py" <codecraig at gmail.com> schrieb im Newsbeitrag
news:1132233527.222443.139470 at g14g2000cwa.googlegroups.com...
> I have a python script that I want to test/debug.  It contains a class
> which extends from some other class which is located in some other
> python file in a different directory.
>
> For example:
>
> [script to test]
> c:\python_code\foo.py
>
> [needed python files]
> c:\some\other\directory\bar.py
>
> ...so I want to test/debug foo.py, which needs bar.py.  foo.py imports
> bar.py ...but in order to test out foo (in the python shell) I normally
> copy bar.py into the same directory as foo.py...but this is painful.
> Is there some way that I can have python know about the directory where
> bar.py is located, like a system variable, etc?  If so, how do I set
> that up?
>
> Thanks.
>





More information about the Python-list mailing list