PYTHONPATH » erst ich, dann Python

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
droptix
User
Beiträge: 521
Registriert: Donnerstag 13. Oktober 2005, 21:27

Ich möchte ein Python-Programm ausliefern. Durch verschiedene Python-Versionen auf den Endrechnern gibt es verschiedene Voraussetzungen. Ich möchte Python 2.3 voraussetzen, allerdings benutze ich auch Module aus Python 2.4 und 2.5. Daher möchte ich diese Module gleich mitliefern, allerdings strukturiere ich diese in Unterordnern meines Programms.

Was ist der beste Weg, um dem Python-Interpreter mitzuteilen, dass er die mitgelieferten Module bevorzugen soll?

Beispiel:

import decimal (ab Python 2.4) sucht zuerst in `./modules/python/`. Wenn dort keine Datei namens `decimal.py(c)` zu finden ist, dann suche in den Python-Bibliotheken, ansonsten raise ImportError.

Das hier steht zum PYTHONPATH in einem schlauen Büchlein:
Python Pocket Reference, Second Edition; Mark Lutz; O'Reilly Verlag; 2002 hat geschrieben:Augments the default search path for module files. The format is the same as the shell's PATH setting: directory pathnames separated by colons (semicolons on DOS). On module imports, Python searches for the correspondig file in each listed directory, from left to right. Merged into sys.path.

sys.path

List of strings specifying module import search path. Initialized from PYTHONPATH shell variable and any installation-dependent defaults. Writable; e.g. sys.path.append('C:\\dir') adds a directory to the search path within a script.

The first item, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g., if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current working directory first. The script directory is inserted before the entries from PYTHONPATH.
Benutzeravatar
gerold
Python-Forum Veteran
Beiträge: 5555
Registriert: Samstag 28. Februar 2004, 22:04
Wohnort: Oberhofen im Inntal (Tirol)
Kontaktdaten:

Hallo droptix!

Code: Alles auswählen

import os
import sys
APPDIR = os.path.dirname(os.path.abspath(sys.argv[0]))
MODULEDIR = os.path.join(APPDIR, "modules", "python")
sys.path.insert(0, MODULEDIR)
import irgendetwas
import nochetwas
mfg
Gerold
:-)
http://halvar.at | Kleiner Bascom AVR Kurs
Wissen hat eine wunderbare Eigenschaft: Es verdoppelt sich, wenn man es teilt.
Antworten