Making code run in both source tree and installation path

ryles rylesny at gmail.com
Wed Jul 1 00:52:52 EDT 2009


On Jun 29, 12:20 pm, Javier Collado <javier.coll... at gmail.com> wrote:
> Hello,
>
> I would like to be able to run the main script in a python project
> from both the source tree and the path in which it's installed on
> Ubuntu. The script, among other things, imports a package which in
> turns makes use of some data files that contains some metadata that is
> needed in xml format.
>
> The source tree has an structure such as this one:
> setup.py
> debian/ (packaging files)
> src/ (source code)
> src/lib (package files)
> src/data (data files)
> src/bin (main script)
>
> However, when the project is installed using setup.py install, the
> directory structure is approximately this way:
> /usr/local/bin (main script)
> /usr/local/share/<project_name> (data files)
> /usr/local/lib/python2.x/dist-packages/<project_name> (library files)
>
> And when installing the code through a package, the structure is the
> same one, but removing "local".
>
> Hence, the data files aren't always in the same relative directories
> depending on we're executing code from the source tree or from the
> installation. To make it possible to run the code from both places,
> I've seen different approaches:
> - distutils trick in setup.py to modify the installed script (i.e.
> changing a global variable value) so that it has a reference to the
> data files location.
> - Heuristic in the package code to detect when it's being executed
> from the source tree and when it has been the installed
> - Just using an environment variable that the user must set according
> to his needs
>
> I guess that there are other options, for example, maybe using
> buildout. What would you say it's the best/more elegant option to
> solve this problem?
>
> Best regards,
>    Javier

It's kludgey, but one option may be to try and use __file__ to figure
out where the script is installed. Something like os.path.dirname
(os.path.abspath(__file__)) could tell you if it's in src/ or in the
bin/ directory, and then data files could be found in the appropriate
place.

I like the distutils/variable option better. Your script is more
likely to still behave correctly when copied to another directory.
Plus its code definitely remains cleaner.



More information about the Python-list mailing list