Reputation: 8027
I need a method to get the data from an external editor.
def _get_content():
from subprocess import call
file = open(file, "w").write(some_name)
call(editor + " " + file, shell=True)
file.close()
file = open(file)
x = file.readlines()
[snip]
I personally think there should be a more elegant way. You see, I need to interact with an external editor and get the data.
Do you know any better approaches/have better ideas?
EDIT:
Marcelo brought me on the idea of using tempfile
for doing that.
Here's how I do it:
def _tempfile_write(input):
from tempfile import NamedTemporaryFile
x = NamedTemporaryFile()
x.file.write(input)
x.close()
y = open(x)
[snip]
This does the job, but also not quite satisfying. Heard something about spawning?..
Upvotes: 1
Views: 2980
Reputation: 42825
I'd recommend using a list, not a string:
def _get_content(editor, initial=""):
from subprocess import call
from tempfile import NamedTemporaryFile
# Create the initial temporary file.
with NamedTemporaryFile(delete=False) as tf:
tfName = tf.name
tf.write(initial)
# Fire up the editor.
if call([editor, tfName]) != 0:
return None # Editor died or was killed.
# Get the modified content.
with open(tfName).readlines() as result:
os.remove(tfName)
return result
Upvotes: 2
Reputation: 342949
an editor just lets you edit a file interactively. you can also edit files with Python. there's no need to call external editor.
for line in open("file"):
print "editing line ", line
# eg replace strings
line = line.replace("somestring","somenewstring")
print line
Upvotes: 1
Reputation: 186068
This is the way all programs do it, AFAIK. Certainly all version control systems that I've used create a temporary file, pass it to the editor and retrieve the result when the editor exits, just as you have.
Upvotes: 3