Git diff抱怨说,“外部差异死了,停在......”我的python diff程序

时间:2013-06-13 01:41:26

标签: python git subprocess return-value git-diff

这是我的差异的开始部分。

#!/usr/bin/env python
import fileinput
import difflib
import subprocess
import sys

# for debugging
def info(type, value, info):
    import traceback
    traceback.print_exception(type, value, info)
    print
    pdb.pm()

sys.excepthook = info
import pdb
#end debugging

if len(sys.argv) == 8:
    # assume this was passed to git; we can of course do
    # some parsing to check if we got valid git style args
    args = [sys.argv[2], sys.argv[5]]
elif len(sys.argv) == 3:
    args = sys.argv[1:]
else:
    exit("Not a valid number of args (2 or 7) to this diff program")
print "Files: " + ' '.join(args)
for filename in args:
    filetype = subprocess.check_output(['file', filename])
    if filetype.find('text') == -1:
        args.insert(0, 'diff')
        print "A binary file was found: " + filename + ", deferring to diff"
        exit(subprocess.call(args))

当遇到二进制(或非文本)文件时,它会尝试fork diff以获取二进制文件是否不同。目标是将这个python diff程序用作git的外部不同。

但我得到了这个可怕的“外部差异死亡,停在< file>”消息一旦命中二进制文件。

git如何评估我的程序?怎么知道它死了?返回值是不是表示不同的条件?

1 个答案:

答案 0 :(得分:2)

您的代码中没有退出功能。如何将exit替换为sys.exit

#!/usr/bin/env python

import subprocess
import sys

if len(sys.argv) == 8:
    # assume this was passed to git; we can of course do
    # some parsing to check if we got valid git style args
    args = [sys.argv[2], sys.argv[5]]
elif len(sys.argv) == 3:
    args = sys.argv[1:]
else:
    print "Not a valid number of args (2 or 7) to this diff program"
    sys.exit(1)
print "Files: ", args
for filename in args:
    filetype = subprocess.check_output(['file', filename])
    if filetype.find('text') == -1:
        args.insert(0, 'diff')
        print "A binary file was found: " + filename + ", deferring to diff"
        #sys.stdout.flush()
        subprocess.call(args)
        sys.exit(0)

编辑:git depend on external diff's exit status. diff仅在没有差异时退出0。所以改变了代码,不要使用diff的退出状态。

PS:没有sys.stdout.flush(),diff输出在print输出之前。