Question

I am creating a tempFile and then adding text to it by opening it with an editor(so that user can enter his message), and then save it to read the text from save NamedTemporaryFile.

with tempfile.NamedTemporaryFile(delete=False) as f:
    f.close()
    if subprocess.call([editor.split(" ")[0], f.name]) != 0:
        raise IOError("{} exited with code {}.".format(editor.split(" ")[0], rc))
    with open(f.name) as temp_file:
        temp_file.seek(0)
        for line in temp_file.readlines():
            print line

But every time it is coming out to be blank. why is it so ?

Était-ce utile?

La solution

If you are using SublimeText as the editor, you will need to pass in the -w or --wait argument to make sure that the Python program waits until you actually close SublimeText again.

Otherwise, you would just start to edit the file, and immediately try to read its contents which at that point are empty.

You could also verify that, by putting in a print before reading the file.

E.g.:

editor = ['/path/to/sublime_text', '-w']

with tempfile.NamedTemporaryFile(delete=False) as f:
    f.close()
    if subprocess.call(editor + [f.name]) != 0:
        raise IOError()

    # read file…

Autres conseils

Here's a solution without editor interaction since I don't have enough information to mimic your editor setup.

import tempfile

with tempfile.NamedTemporaryFile(delete=False) as f:
    f.close()
    with open(f.name, f.mode) as fnew:
        # Replace with editor interaction
        fnew.write('test')
        fnew.seek(0)
        for line in fnew.readlines():
            print line

At least on my system and version (2.7.2), I had to make these changes to allow the file object to be properly reopened and interacted with, and it builds correctly in Sublime. f.name is the temporary file path, and f.mode is the mode used by the already closed file (in this case it should default to 'w+b').

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top