Editing text with an external editor in Python

Zachary Ware zachary.ware+pylist at gmail.com
Tue Sep 2 23:03:25 EDT 2014


On Tue, Sep 2, 2014 at 3:45 AM, Chris Angelico <rosuav at gmail.com> wrote:
> Considering how easy it is to deploy a multi-line edit widget in any
> GUI toolkit, it shouldn't be too hard to write a GUI text editor.

Coincidentally, I was annoyed enough to write the following program
sometime last week.  I was sick of messing with Notepad or Notepad++
as the git editor (and don't feel like learning vim just to write a
commit message), so I took 10 minutes to write this, packaged it up
with py2exe and pointed git at it.  Works like a charm for me!

#!C:/Python34/python.exe
"""Simple commit message tool.

Dead simple tkinter GUI for writing commit messages for git without messing
around with Notepad's line ending stupidity or Notepad++ being open or not.
"""

import os
import sys
import tkinter as tk

class Committer:
    def __init__(self, root, filename):
        self.root = root
        self.root.protocol('WM_DELETE_WINDOW', self.destroy)
        self.filename = filename
        self.text = tk.Text(root)
        self.text['width'] = 80
        self.text['height'] = 25
        self.text.pack()
        self.text.focus()
        with open(self.filename) as f:
            self.text.insert('end', f.read())
            self.text.mark_set("insert", "1.0")

    def destroy(self):
        message = self.text.get('1.0', 'end')
        with open(self.filename, 'w') as f:
            f.write(message)
        self.root.destroy()

def main():
    root = tk.Tk()
    assert os.path.exists(sys.argv[1]), sys.argv[1]
    committer = Committer(root, sys.argv[1])
    root.mainloop()

if __name__ == '__main__':
    main()

-- 
Zach



More information about the Python-list mailing list