Can Python Module Locate Itself?
Skip Montanaro
skip at pobox.com
Wed Sep 17 10:33:14 EDT 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:
#!/usr/bin/env python
"""
Python Script Template
usage %(prog)s [ -h ] ...
-h - print this documentation and exit.
"""
import sys
import getopt
prog = sys.argv[0]
def usage(msg=None):
if msg is not None:
print >> sys.stderr, msg
print >> sys.stderr, __doc__.strip() % globals()
def main(args):
try:
opts, args = getopt.getopt(args, "h", ["--help"])
except getopt.GetoptError, msg:
usage(msg)
return 1
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
return 0
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
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.)
Skip
More information about the Python-list
mailing list