Start New Discussion within our Software Development Community

This small script named sourcecode.py is a command line tool to open a python module's source file with the default editor. For example the line

$ python sourcecode.py xml.dom.minidom

opens the file minidom.py from the python distribution with the default editor. The same works with user-defined modules having a python source file.

#!/usr/bin/env python
# -*-coding: utf8-*-
# Title: sourcecode.py
# Python version: >= 2.7
# Author: Gribouillis for the python forum at www.daniweb.com
# Created: 2012-01-01 12:10:03.179236 (isoformat date)
# License: Public Domain
# Use this code freely.
"""Script to find and edit the source code of a python module."""

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
import argparse
import os.path

__version__ = '0.2.5'

def main(args):
    modname = args.modname
    do_find = True
    if '.' in modname:
        packagename, modname = modname.rsplit('.', 1)
        import importlib
        package = importlib.import_module(packagename)
        try:
            a = (package.__path__,)
        except AttributeError:
            # handle special cases such as os.path (os is not a package)
            f = importlib.import_module(args.modname).__file__
            do_find = False
    else:
        a = ()
    if do_find:
        import imp
        file, f, description =  imp.find_module(modname, *a)
    if f.endswith((".pyc", ".pyo")):
        if os.path.isfile(f[:-1]):
            f = f[:-1]
    elif os.path.isdir(f) and os.path.isfile(os.path.join(f, '__init__.py')):
        f = os.path.join(f, '__init__.py')
    if f.endswith(".py"):
        import webbrowser
        webbrowser.open(f)
    else:
        print('Found at {} (no *.py file to edit).'.format(repr(f)))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description = """Open a python module's source file with default editor.
        
        Only filenames with extension '.py' are opened.""",
        formatter_class =argparse.RawTextHelpFormatter,
    )
    parser.add_argument('modname',
        action = 'store',
        help = 'Module name (may contain dots, e.g xml.dom)',
        metavar = 'MODNAME',
    )
    args = parser.parse_args()
    main(args)
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.