Python从临时文件读取未成功

Python从临时文件读取未成功,python,subprocess,readfile,temporary-files,Python,Subprocess,Readfile,Temporary Files,。。。打开我的升华文本,但当我输入一些东西并关闭文件时,我没有得到任何输出或错误,只有一个空行(在Python 2上)。是的,程序会一直等到我写完 编辑: 我刚刚发现这可能是Sublime Text特有的问题,因为vi、emacs和nano在作为编辑器输入时都可以正常工作。 但我仍然想知道如何解决这个问题 根据“编辑”部分,您可以保存该文件,然后重新打开它,这可能不是最佳解决方案,也不会“解决”原始问题,但至少应该可以: with tempfile.NamedTemporaryFile(dele

。。。打开我的升华文本,但当我输入一些东西并关闭文件时,我没有得到任何输出或错误,只有一个空行(在Python 2上)。是的,程序会一直等到我写完

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

根据“编辑”部分,您可以保存该文件,然后重新打开它,这可能不是最佳解决方案,也不会“解决”原始问题,但至少应该可以:

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

它的工作原理与直接写入输出文件的情况相同:

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()
如果编辑器先写入自己的临时文件,然后在最后重命名,则失败:

#!/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')
#!/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)