Changing script's search path at install time

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Dec 20 05:07:44 EST 2014


Mitko Haralanov wrote:

> Hi all,
> 
> I have a question regarding installation of Python scripts and modules
> using distutils that I can't find an answer to by searching through Google
> and the Python website. Hopefully, someone on this list might have ideas?
> 
> I am writing a Python app, which I would eventually like to install using
> disutils. The app has the current tree strucutre:
> 
> <root>
>   |----- myapp.py
>   |----- modules/
>                |------  lib/
>                          |------  __init__.py
>                          |------  mymodule1.py
>                          |------  mymdule2.py
>                |------- cmds/
>                          |------  __init__.py
>                          |------  cmds1.py


Have you considered making the whole app a single package, and getting rid
of the unnecessary (so it seems to me) "modules" directory?

<root>
  +-- myapp/
      +-- __init__.py
      +-- __main__.py
      +-- lib/
          +-- contents of lib
      +-- cmds/
          +-- contents of cmds

The __main__.py is run when you do:

python -m myapp


without needing to know the exact path to it. (So long as it can be found on
the Python path.) That may simplify your development.

If you still insist on having a file myapp.py which appears elsewhere, say
in your home directory, it can include a little hack at the start:

# Untested, and probably not quite enough to work correctly.
import sys
if '.' in sys.path:
    sys.path.remove('.')
import myapp


which is a way of ensuring that the installed myapp *package* shadows the
currently-running myapp.py *module*.

(This, I hasten to add, is a nasty dirty hack. A less nasty way to do this
is to just make the local myapp.py a symlink or hard link to the real
myapp/__main__.py. Better still is not to use the same name for the package
and the script.)




-- 
Steven




More information about the Python-list mailing list