Он работает, если выходной файл записывается непосредственно:
#!/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)
Является редактором строка? В этом случае сам вызов подпроцесса терпит неудачу, так как вы добавите строку и список вместе – thiruvenkadam
Это фактически список. –