3

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

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

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

但是一旦遇到二进制文件,我就会收到这个可怕的“外部差异死亡,在 <file> 处停止”消息。

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

4

1 回答 1

2

您的代码中没有退出功能。换成怎么exitsys.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取决于外部差异的退出状态。 diff仅当没有差异时才以 0 退出。所以更改了代码不使用 diff 的退出状态。

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

于 2013-06-13T05:31:05.797 回答