在Python3中:'str' does not support the buffer interface$ python3 editor.py
Traceback (most recent call last):
File "editor.py", line 9, in
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
对于python3,使用initial_message = b""声明缓冲字符串。
然后使用edited_message.decode("utf-8")将缓冲区解码为字符串。import sys, tempfile, os
from subprocess import call
EDITOR = os.environ.get('EDITOR','vim') #that easy!
initial_message = b"" # if you want to set up the file somehow
with 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"))
结果:$ python3 editor.py
look a string