完全無關的.flush()
的問題,你可以通過stdin傳遞一個文件,而不是寫在磁盤上的內容:
from tempfile import NamedTemporaryFile
from subprocess import Popen, PIPE
with NamedTemporaryFile() as file:
file.write(prod_notes)
file.flush()
p = Popen(['diff', '-', file.name], stdin=PIPE)
p.communicate(stage_notes) # diff reads the first file from stdin
if p.returncode == 0:
print('the same')
elif p.returncode == 1:
print('different')
else:
print('error %s' % p.returncode)
diff
從標準輸入讀取IF輸入文件名是-
。
如果您使用命名管道,那麼你就不需要寫在所有的磁盤上的內容:
from subprocess import Popen, PIPE
from threading import Thread
with named_pipe() as path:
p = Popen(['diff', '-', path], stdin=PIPE)
# use thread, to support content larger than the pipe buffer
Thread(target=p.communicate, args=[stage_notes]).start()
with open(path, 'wb') as pipe:
pipe.write(prod_notes)
if p.wait() == 0:
print('the same')
elif p.returncode == 1:
print('different')
else:
print('error %s' % p.returncode)
其中named_pipe()
上下文管理被定義爲:
import os
import tempfile
from contextlib import contextmanager
from shutil import rmtree
@contextmanager
def named_pipe(name='named_pipe'):
dirname = tempfile.mkdtemp()
try:
path = os.path.join(dirname, name)
os.mkfifo(path)
yield path
finally:
rmtree(dirname)
內容一個命名管道不接觸磁盤。
來源
2014-04-23 00:04:54
jfs
你試過了嗎:['print(''。join(difflib.ndiff(stage_notes,prod_notes)))'](https://docs.python.org/2/library/difflib.html#difflib.ndiff )而不是? – jfs