Appending to sys.path

Peter Otten __peter__ at web.de
Tue Mar 24 17:01:10 CET 2009


mhearne808[insert-at-sign-here]gmail[insert-dot-here]com wrote:

> I have an application where I would like to append to the python path
> dynamically.  Below is a test script I wrote.  Here's what I thought
> would happen:
> 
> 1) I run this script in a folder that is NOT already in PYTHONPATH
> 2) The script creates a subfolder called foo.
> 3) The script creates a file called foo.py, with a foo() method
> defined in it.
> 4) The script attempts to import this module, which fails because the
> current folder is not in PYTHONPATH.
> 5) The script then adds the current folder to the end of sys.path
> 6) The script again attempts to import foo.foo, and succeeds.
> 
> #6 never happens, but I can't figure out why.  I'm running on Mac OS
> 10.5, with python 2.5.1.
> 
> Anybody have any tips?
> 
> Thanks,
> 
> Mike
> 
> Here's the script:
> #!/usr/bin/python
> 
> import sys
> import os.path
> 
> txt = 'def foo(): print "Hello world!"\n'
> if not os.path.isdir('foo'):

Here you add a directory under the current working directory.

>     os.mkdir('foo')
> f = open('foo/foo.py','wt')
> f.write(txt)
> f.close()

To turn the foo directory into a package you must also create a file
foo/__init__.py (may be empty).
> 
> try:
>     __import__('foo.foo')
> except ImportError:
>     homedir = os.path.abspath(sys.path[0]) #where is this script?
>     print 'Adding %s to sys.path' % (homedir)
>     sys.path.append(homedir)

Here you add the directory to the path were the script is located, not the
cwd. Should be

     sys.path.append(".")

>     try:
>         __import__('foo.foo')
>         print 'Import now successful'
>     except ImportError:
>         print "Why didn't this work?"
>         sys.exit(1)

Peter




More information about the Python-list mailing list