How to launch an EDITOR (e. g. vim) from a python script?
Calling up $EDITOR is easy. I've written this kind of code to call up editor:
import sys, tempfile, osfrom subprocess import callEDITOR = os.environ.get('EDITOR','vim') #that easy!initial_message = "" # if you want to set up the file somehowwith tempfile.NamedTemporaryFile(suffix=".tmp") as tf: tf.write(initial_message) tf.flush() call([EDITOR, tf.name]) # do the parsing with `tf` using regular File operations. # for instance: tf.seek(0) edited_message = tf.read()
The good thing here is, the libraries handle creating and removing the temporary file.
In python3: 'str' does not support the buffer interface
$ python3 editor.pyTraceback (most recent call last): File "editor.py", line 9, in <module> tf.write(initial_message) File "/usr/lib/python3.4/tempfile.py", line 399, in func_wrapper return func(*args, **kwargs)TypeError: 'str' does not support the buffer interface
For python3, use initial_message = b""
to declare the buffered string.
Then use edited_message.decode("utf-8")
to decode the buffer into a string.
import sys, tempfile, osfrom subprocess import callEDITOR = os.environ.get('EDITOR','vim') #that easy!initial_message = b"" # if you want to set up the file somehowwith tempfile.NamedTemporaryFile(suffix=".tmp") as tf: tf.write(initial_message) tf.flush() call([EDITOR, tf.name]) # do the parsing with `tf` using regular File operations. # for instance: tf.seek(0) edited_message = tf.read() print (edited_message.decode("utf-8"))
Result:
$ python3 editor.pylook a string
Package python-editor
:
$ pip install python-editor$ python>>> import editor>>> result = editor.edit(contents="text to put in editor\n")
More details here: https://github.com/fmoo/python-editor