Welcome, guest | Sign In | My Account | Store | Cart

This is a very basic example of how to launch an editor from inside a program. NOTE: a real script would have all sorts of error management wrapped around it, using this as is may cause baldness, impotence, priapism or worse. Will not work for windows.

Python, 18 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python

import os
from tempfile import NamedTemporaryFile

def edit(filehandle):
    """spawns an editor returns the file as a string; by default uses emacs if
    EDITOR is not defined in the environment, expects a filehandle as returned
    by NamedTemporaryFile()"""
    editor = os.getenv('EDITOR','emacs')
    x = os.spawnlp(os.P_WAIT,editor,editor,filehandle.name)
    if x != 0:
        print "ERROR"
    return filehandle.read()

if __name__=='__main__':
    fd = NamedTemporaryFile()
    text = edit(fd)

This is one of those little things that can save lots of time. I've used variants of this for mangling configurations, writing blog posts, sending emails,etc. Pretty much anywhere where the user needs to edit more than one line of text.

You can make your scripts simpler and more effective using an input>parse>if-error-re-edit cycle that gives your users immediate feedback if they make a mistake in setting up the configuration file. Most editors on unix understand the '+n' format for determining the line number to put the point at and you can use that to send someone to the line they need.

Since I didn't find a direct explanation of how to do this via google i figured I'd write it up and pass it on.