Skip to content

Instantly share code, notes, and snippets.

@waylan
Created March 28, 2012 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waylan/2228132 to your computer and use it in GitHub Desktop.
Save waylan/2228132 to your computer and use it in GitHub Desktop.
Edit text in the system default text editor (using Envrion vars if set)
from __future__ import print_function
import os
import sys
from tempfile import mkstemp
from subprocess import call
def run_editor(txt):
""" Edit the given text in the system default text editor. """
# Create temp file
fd, tmpfile = mkstemp()
os.write(fd, txt or "")
os.close(fd)
# Set some basic default editors
editor = "vi"
if sys.platform == "win32":
editor = "notepad"
# Now check for Evironment variables
if os.environ.has_key("VISUAL"):
editor = os.getenv("VISUAL")
elif os.environ.has_key("EDITOR"):
editor = os.getenv("EDITOR")
# Run the editor
try:
retcode = call("%s %s" % (editor, tmpfile), shell=True)
except OSError, e:
print("Execution failed:", e, file=sys.stderr)
os.unlink(tmpfile)
# Get contents and delete temp file
contents = open(tmpfile).read()
os.unlink(tmpfile)
return contents
if __name__ == '__main__':
out = run_editor('foo')
if out:
print(out)
else:
# a blank file returned by editor aborts.
print("Aborted!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment