473,657 Members | 2,300 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can Python Module Locate Itself?

sj
I have written several small shell utilities in Python and typically use
comments at the start of the source file as documentation. A command line
option allows the user to read this documentation. The problem is that I
have to explicitly code the source files location within the source which
is not very portable. Is there anyway for a python module to locate its
own source ?

Thanks
Jul 18 '05 #1
6 4269
sj <_r************ *@swbell.net> writes:
I have written several small shell utilities in Python and typically use
comments at the start of the source file as documentation. A command line
option allows the user to read this documentation. The problem is that I
have to explicitly code the source files location within the source which
is not very portable. Is there anyway for a python module to locate its
own source ?


I don't know about locating source, but does the documentation have to
be in comments? I think documentation strings exist for this purpose.

example.py:
"""
This is an example file. By using command line argument '-h' user can
print this documentation.
"""
import sys
if sys.argv[1] == "-h":
print __doc__


--
Juha Autero
http://www.iki.fi/jautero/
Eschew obscurity!
Jul 18 '05 #2
Try this:

print 'usage:', __file__

Kerim

Jul 18 '05 #3
Hello sj,
I have written several small shell utilities in Python and typically use
comments at the start of the source file as documentation. A command line
option allows the user to read this documentation. The problem is that I
have to explicitly code the source files location within the source which
is not very portable. Is there anyway for a python module to locate its
own source ?

sys.argv[0] is always the name of the script.

Have you looked at the new optparse module?
(http://www.python.org/doc/current/li...-optparse.html)

HTH.
Miki
Jul 18 '05 #4

You can use sys.argv[0] to get the path of the program and use that to
read in the program file.. you could then parse the source as usual.

But personally i'd be enclined to go with Juha's idea, it seems more
elegant and requires less work on the part of the program and the
programmer..

Have fun,

Mark.
--
Posted via http://dbforums.com
Jul 18 '05 #5

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(a rgs, "h", ["--help"])
except getopt.GetoptEr ror, 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(s ys.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

Jul 18 '05 #6
sj
Thanks all for the many useful suggestions.

One of the reasons I placed the docs in comments is that I have a modified
version of head which outputs the initial comment block of a file. Its
smart enough to recognize c++, java, python and lisp commenting styles. On
reflection I'm not sure this approach offers any advantage over the elegant
and standard python doc string. Also it would be easy to to update the
modified head program to look for any initial doc strings.
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
3651
by: Jeffrey Barish | last post by:
Since upgrading to python 2.4 yesterday, I am no longer able to use Tkinter. From http://www.python.org/moin/TkInter I learned that I need to edit Modules/Setup to include Tkinter during the make. However, it isn't clear to me what modifications to make. I am supposed to specify directories in which needed files can be found. I found the Tcl/Tk libraries in /usr/local/lib/python2.4/lib-tk, but I can't find the Tcl/Tk headers. The...
25
7743
by: Xah Lee | last post by:
Python Doc Problem Example: gzip Xah Lee, 20050831 Today i need to use Python to compress/decompress gzip files. Since i've read the official Python tutorial 8 months ago, have spent 30 minutes with Python 3 times a week since, have 14 years of computing experience, 8 years in mathematical computing and 4 years in unix admin and perl, i have quickly found the official doc: http://python.org/doc/2.4.1/lib/module-gzip.html
3
5666
by: JimF | last post by:
I need to scan a couple of hundred databases in several directories to locate all code that uses a particular function, but cannot figure out how to read the Form or Module text itself. I am able to locate, then connect to the databases, and have figured out how to get the Form and Module names easy enough using the documents collection of each of the Form and Module containers, but how do I actually read the code to find out which...
3
3710
by: skip | last post by:
I'm having no success building the curses module on Solaris 8 (yes, I know it's ancient - advancing the state-of-the-art is not yet an option) for Python 2.4. Sun provides an apparently ancient version of curses in /usr/lib, so I downloaded and installed ncurses 5.5, both using default settings and using --with-shared. When the curses module is linked against libcurses.so I get some strange error about acs32map being undefined (which...
0
1542
by: has | last post by:
Hi all, need a little bit of advice on dynamically binding an embedded Python interpreter. First, the code for anyone that wants a look: http://trac.macosforge.org/projects/appscript/browser/py-osacomponent/trunk/PyOSA It's a Python OSA component for OS X. The idea is that you wrap up a scripting language interpreter as a Carbon Component Manager component (similar to writing a COM component); applications can then call the
206
8287
by: WaterWalk | last post by:
I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a footprint which says: "Indeed, one often hears arguments against building exibility into an engineered sys- tem. For example, in the philosophy of the computer language Python it is claimed: \There should be one|and preferably only one|obvious...
3
2661
by: Philip Semanchuk | last post by:
On Nov 9, 2008, at 7:00 PM, News123 wrote: Look under the heading "Standard Encodings": http://docs.python.org/library/codecs.html Note that both the page you found (which appears to be a copy of the Python documentation) and the reference I provide say, "Neither the list of aliases nor the list of languages is meant to be exhaustive".
0
8411
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8323
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8739
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2740
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1969
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.