#!/usr/bin/env python2 VERSION = 0.2 # origin_dir - Get directory where this program is located. # # Copyright (C) 2001 Peter Åstrand # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # Usage 1: Import in Python application and run get_origin_dir() to fetch # origin directory. # # Usage 2: Use as an wrapper for a binary that needs to now its own location. # Rename to . # Copy this program to (must be in same directory as ). # Change PROGRAM_BINARY below to . # can now look at environment variable PROGRAM_ORIGIN_DIR to # get its location. It can also look at argv[0], which is an absolute path. # # Usage3: Use origin_dir.py in a shellscript, to get the scripts location. # Make sure origin_dir.py is installed somewhere where Python can find it. # Include the following line at top of the shell script: # ORIGIN_DIR=`python -c "import origin_dir; print origin_dir.get_origin_dir(\"$0\")"` # # The scripts location is now in the environment variable ORIGIN_DIR. PROGRAM_BINARY = "myapp.bin" import os import sys import string def realpath(filename): """Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.""" filename = os.path.abspath(filename) bits = ['/'] + string.split(filename, '/')[1:] for i in range(2, len(bits)+1): component = apply(os.path.join, bits[0:i]) if os.path.islink(component): resolved = os.readlink(component) (dir, file) = os.path.split(component) resolved = os.path.normpath(os.path.join(dir, resolved)) newpath = apply(os.path.join, [resolved] + bits[i:]) return realpath(newpath) return filename def get_origin_dir(argv0=sys.argv[0]): """Get program origin directory""" abs_path = realpath(os.path.abspath(argv0)) return os.path.dirname(abs_path) if __name__ == "__main__": origin_dir = get_origin_dir() os.putenv("PROGRAM_ORIGIN_DIR", origin_dir) sys.argv[0] = os.path.join(origin_dir, PROGRAM_BINARY) os.execv(sys.argv[0], sys.argv)