Launch default editor for python module.

Updated Gribouillis 2 Tallied Votes 628 Views Share

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

$ python xml.dom.minidom

opens the file 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:
# Python version: >= 2.7
# Author: Gribouillis for the python forum at
# 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)
            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
        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, '')):
        f = os.path.join(f, '')
    if f.endswith(".py"):
        import webbrowser
        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,
        action = 'store',
        help = 'Module name (may contain dots, e.g xml.dom)',
        metavar = 'MODNAME',
    args = parser.parse_args()