Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intelligently launching the default editor from inside a Python CLI program?

Tags:

python

editor

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?

like image 595
Paul Hoffman Avatar asked Dec 06 '09 22:12

Paul Hoffman


2 Answers

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.

like image 118
Ned Batchelder Avatar answered Nov 08 '22 04:11

Ned Batchelder


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.

like image 43
Seth Avatar answered Nov 08 '22 02:11

Seth