4/19/2004

openit

For a while now I have been using a very useful one-off script I wrote which I call 'openit'. You provide it with the dotted name of any python package or module, and it opens it in your editor. You don't have to worry whether the module is in the stdlib, in your sitepackages, or somewhere else on your pythonpath. I have been using it more and more recently, and the implementation is trivial, so I thought I would share it here:




#!/usr/bin/python

import os, sys

numargs = len(sys.argv)
if numargs == 1 or numargs > 2:
print """Usage: %s modulename""" % sys.argv[0]
sys.exit()

from twisted.python import reflect

obj = reflect.namedAny(sys.argv[1])

fileName = obj.__file__
if fileName[-1] == 'c':
fileName = fileName[:-1]

os.system("open %s" % fileName)


This implementation uses twisted.python because it is convenient, but the implementation of namedAny is short enough that you could really just copy it into the script if you wanted to. It also uses the Mac OS X specific 'open' command, so you will have had to tell the Finder which application you want to edit .py files. If you are on any other OS besides OS X, you can replace the open command with $EDITOR or whatever command you use to edit a file with your editor of choice.



2 comments:

Mark Eichin said...

I got as far as this "pyless" script:
#!/usr/bin/python
import os, sys
os.spawnlp(os.P_WAIT, "less", "less", __import__(sys.argv[1]).__file__.replace(".pyc",".py"))
before realizing (1) how perlish it looked (2) that I'm already in emacs most of the time, and I'd need a python-mode/comint of some sort to do what I really wanted, namely pop it up in emacs (maybe just using emacsclient there is sufficient, though. or os.getenv("PAGER")...)

Stephen Thorne said...

What you need is to incorporate this with ctags! So you can generate a super-tagfile that respects module, classes and function identifiers.
Both vim and emacs support ctags.