tags:

views:

87

answers:

2

The answers in this question didn't get to the heart of the problem. In a CLI-based Python program, I want the user to be able to edit a file and then return to the program. Before returning, I want them to be able to cancel their edits. This should feel like the commit-note-editing feature in Subversion.

What are the current best practices for this type of task?

+2  A: 

Subversion, et al use the $EDITOR environment variable to determine which program to use to edit text files. Of course, $EDITOR will only work if you're on a unixy platform in a shell. You'll have to do something different for Windows (cmd /c start tempfile.txt) or Mac OS X (open tempfile.txt).

But, this is essentially what the answers and related answers to your other question said.

If you just want to be able to "cancel" edits, then make a temporary copy of the file, and invoke your editor on that. Your program can then copy the contents of the temporary file into the real file or, if the user cancels, don't. This is basically how Subversion does it.

Seth
+5  A: 

You could try looking through the sources to Mercurial, which is written in Python.

They use os.environ to read the value of environment variables HGEDITOR, VISUAL, and EDITOR, defaulting to vi. Then they use os.system to launch the editor on a temp file created with tempfile.mkstemp. When the editor is done, they read the file. If it has any real content in it, the operation continues, otherwise, it is aborted.

If you want to see how Mercurial does it, the details are in ui.py and util.py.

Ned Batchelder