就像直接写入输出文件一样工作:
#!/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)