Can Python Module Locate Itself?
skip at pobox.com
Wed Sep 17 16:33:14 CEST 2003
sj> I have written several small shell utilities in Python and typically
sj> use comments at the start of the source file as documentation. A
sj> command line option allows the user to read this documentation. The
sj> problem is that I have to explicitly code the source files location
sj> within the source which is not very portable. Is there anyway for a
sj> python module to locate its own source ?
This doesn't answer your question about locating the source file (yes, you
can most of the time, check the __file__ global), but I start out with this
template when creating a new script:
Python Script Template
usage %(prog)s [ -h ] ...
-h - print this documentation and exit.
prog = sys.argv
if msg is not None:
print >> sys.stderr, msg
print >> sys.stderr, __doc__.strip() % globals()
opts, args = getopt.getopt(args, "h", ["--help"])
except getopt.GetoptError, msg:
for opt, arg in opts:
if opt in ("-h", "--help"):
if __name__ == "__main__":
This guarantees I always have a help capability, no matter how trivial.
(This is not original with me. I gleaned all the idioms used in this script
from this group over the years.)
More information about the Python-list