newbie question: how to run a python file if it is in a package

Diez B. Roggisch deets at nospam.web.de
Fri Sep 5 07:12:16 EDT 2008


neoedmund schrieb:
> for example:
> 
> X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y"
> how can I run X.py avoiding it saying such like "ImportError: No
> module named aaa.bbb"?
> 
> Is all runnable script must be in the default package?

There is no such thing as a "default package"

All imports are resolved over the "sys.path" list of directories (or eggs).

There are various ways to modify this:


  - by hand. If you know X.py lives below aaa/bbb, you can get it's
    __file__-attribute, and walk the way down two levels. Then add the
    resulting path to sys.path. All this has to be done before any
    import of aaa.bbb occurs.

  - modify the environment variable PYTHONPATH to contain the root of
    aaa.bbb before starting the script.

  - write a custom .pth-file and place it into your pythno installation.
    The pth-file will contain the above mentioned root path.

  - use setuptools to create script entry-points, and install your whole
    application either fully, or as so-called egg-link. Possibly inside
    a virtualenv. This would be my personally preferred method.

  - simply copy your wohe aaa.bbb-stuff into site-packages. Make sure you
    do that whenever you change something in your code.


Diez



More information about the Python-list mailing list