Created
March 28, 2012 16:49
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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