从tempfile读取的Python不成功

时间:2015-01-21 13:09:30

标签: python subprocess readfile temporary-files

with tempfile.NamedTemporaryFile(delete = False) as tmpfile:
    subprocess.call(editor + [tmpfile.name])    # editor = 'subl -w -n' for example 
    tmpfile.seek(0)
    print tmpfile.read()

...打开我的Sublime Text但是当我输入内容并关闭文件时,我没有输出也没有错误,只是一个空行(在Python 2上)。是的,程序确实等到我写完了。

编辑:
我刚刚发现它可能是Sublime Text特有的问题,因为viemacsnano在作为编辑器输入时都能正常工作。 但我仍然想知道如何解决这个问题。

2 个答案:

答案 0 :(得分:1)

根据"编辑"部分,你可以保存文件,然后重新打开它,这可能不是最好的解决方案,它不会解决"最初的问题,但至少应该有效:

import subprocess
import tempfile

editor = ['gedit']

with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
    subprocess.call(editor + [tmpfile.name])    # editor = 'subl -w -n' for example 
    tmpfile.file.close()
    tmpfile = file(tmpfile.name)
    print tmpfile.read()

答案 1 :(得分:1)

如果直接写入输出文件,它的工作原理如下:

#!/usr/bin/env python
import subprocess
import sys
import tempfile

editor = [sys.executable, '-c', "import sys;"
                                "open(sys.argv[1], 'w').write('abc')"]
with tempfile.NamedTemporaryFile() as file:
    subprocess.check_call(editor + [file.name])
    file.seek(0)
    print file.read() # print 'abc'

如果编辑器首先写入自己的临时文件并在结尾重命名它,则失败:

#!/usr/bin/env python
import subprocess
import sys
import tempfile

editor = [sys.executable, '-c', r"""import os, sys, tempfile
output_path = sys.argv[1]
with tempfile.NamedTemporaryFile(dir=os.path.dirname(output_path),
                                 delete=False) as file:
    file.write(b'renamed')
os.rename(file.name, output_path)
"""]
with tempfile.NamedTemporaryFile() as file:
    subprocess.check_call(editor + [file.name])
    file.seek(0)
    print file.read() #XXX it prints nothing (expected 'renamed')

将文件重新打开为@Vor suggested有助于:

#!/usr/bin/env python
import os
import subprocess
import sys
import tempfile

editor = [sys.executable, '-c', r"""import os, sys, tempfile
output_path = sys.argv[1]
with tempfile.NamedTemporaryFile(dir=os.path.dirname(output_path),
                                 delete=False) as file:
    file.write(b'renamed')
os.rename(file.name, output_path)
"""]
try:
    with tempfile.NamedTemporaryFile(delete=False) as file:
        subprocess.check_call(editor + [file.name])
    with open(file.name) as file:
        print file.read() # print 'renamed'
finally:
    os.remove(file.name)