tags:

views:

73

answers:

3

Hey,

I need a method to get the data from an external editor.

def _get_content():
     from subprocess import call
     file = open(file, "w").write(some_name)
     call(editor + " " + file, shell=True)
     file.close()
     file = open(file)
     x = file.readlines()

     [snip]

I personally think there should be a more elegant way. You see, I need to interact with an external editor and get the data.

Do you know any better approaches/have better ideas?

EDIT:

Marcelo brought me on the idea of using tempfile for doing that.

Here's how I do it:

def _tempfile_write(input):
    from tempfile import NamedTemporaryFile

    x = NamedTemporaryFile()
    x.file.write(input)
    x.close()
    y = open(x)

    [snip]

This does the job, but also not quite satisfying. Heard something about spawning?..

+2  A: 

This is the way all programs do it, AFAIK. Certainly all version control systems that I've used create a temporary file, pass it to the editor and retrieve the result when the editor exits, just as you have.

Marcelo Cantos
Mentioning temporary files was good.. I found a good Python module on that named ``tempfile``. I think this sounds great for the start.
Kenny M.
+1  A: 

an editor just lets you edit a file interactively. you can also edit files with Python. there's no need to call external editor.

for line in open("file"):
    print "editing line ", line
    # eg replace strings
    line = line.replace("somestring","somenewstring")
    print line
ghostdog74
Yes, I know that. Though I need to get user input and then immediately process that data, storing it all in a database, otherwise I'd do it just that way. :)
Kenny M.
+1  A: 

I'd recommend using a list, not a string:

def _get_content(editor, initial=""):
    from subprocess import call
    from tempfile import NamedTemporaryFile

    # Create the initial temporary file.
    with NamedTemporaryFile(delete=False) as tf:
        tfName = tf.name
        tf.write(initial)

    # Fire up the editor.
    if call([editor, tfName]) != 0:
        return None # Editor died or was killed.

    # Get the modified content.
    with open(tfName).readlines() as result:
        os.remove(tfName)
        return result
Mike DeSimone
Thanks Mike. That's a good idea.
Kenny M.
Gah, forgot the justification: You want to use a list to `call` and `shell=False` because then you don't have to worry about escaping any characters in the filename (space, ``, etc.) that the shell gives special meaning to. Granted, `NamedTemporaryFile` shouldn't give you a filename with those characters, but it's a good habit to get into.
Mike DeSimone
Thanks for that hint!
Kenny M.