Editing text with an external editor in Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 1 18:11:34 CEST 2014


Python's input() or raw_input() function is good for getting a single line
of text from the user. But what if you want a more substantial chunk of
text from the user? Here's how to call out to an external editor such as
ed, nano, vim, emacs, and even GUI text editors:

import tempfile

def edit(editor, content=''):
    f = tempfile.NamedTemporaryFile(mode='w+')
    if content:
        f.write(content)
        f.flush()
    command = editor + " " + f.name
    status = os.system(command)
    f.seek(0, 0)
    text = f.read()
    f.close()
    assert not os.path.exists(f.name)
    return (status, text)


Anyone able to test it on Windows for me please?


More here: 

https://code.activestate.com/recipes/578926/


-- 
Steven




More information about the Python-list mailing list