python类context_diff()的实例源码

diff.py 文件源码 项目:bezier 作者: dhermes 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def diff(filename1, filename2):
    if not os.path.exists(filename1):
        msg = NOT_EXISTS.format(filename1)
        print(msg, file=sys.stderr)
        sys.exit(1)

    if not os.path.exists(filename2):
        msg = NOT_EXISTS.format(filename2)
        print(msg, file=sys.stderr)
        sys.exit(1)

    with open(filename1, 'r') as file_obj:
        lines1 = file_obj.readlines()

    with open(filename2, 'r') as file_obj:
        lines2 = file_obj.readlines()

    if lines1 == lines2:
        msg = '{} and {} are identical'.format(filename1, filename2)
        print(msg)
    else:
        diff_lines = difflib.context_diff(
            lines1, lines2, fromfile=filename1, tofile=filename2)
        print(''.join(diff_lines))
        sys.exit(1)
check_doc_templates.py 文件源码 项目:bezier 作者: dhermes 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def get_diff(value1, value2, name1, name2):
    """Get a diff between two strings.

    Args:
        value1 (str): First string to be compared.
        value2 (str): Second string to be compared.
        name1 (str): Name of the first string.
        name2 (str): Name of the second string.

    Returns:
        str: The full diff.
    """
    lines1 = [line + '\n' for line in value1.splitlines()]
    lines2 = [line + '\n' for line in value2.splitlines()]
    diff_lines = difflib.context_diff(
        lines1, lines2, fromfile=name1, tofile=name2)
    return ''.join(diff_lines)
comparators.py 文件源码 项目:webmon 作者: KarolBedkowski 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def compare(self, old: str, old_date: str, new: str, new_date: str,
                ctx: common.Context, meta: dict) \
            -> ty.Tuple[bool, ty.Optional[str], ty.Optional[dict]]:
        # pylint: disable=invalid-sequence-index
        old_lines = old.split('\n')
        res = list(difflib.context_diff(
            old_lines, new.split('\n'),
            fromfiledate=old_date, tofiledate=new_date,
            lineterm='\n'))

        changed_lines = sum(1 for line in res[2:]
                            if line and line[0] != ' ' and line[0] != '*')
        if not _check_changes(ctx, changed_lines, len(old_lines),
                              self.conf.get("changes_threshold"),
                              self.conf.get("min_changed")):
            return False, None, None

        return True, "\n".join(res), self.opts
diff_jsonl.py 文件源码 项目:singer-tools 作者: singer-io 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("file1")
    parser.add_argument("file2")
    args = parser.parse_args()

    lines1 = load_jsonl_file(args.file1)
    lines2 = load_jsonl_file(args.file2)

    pretty_lines1 = prettify(lines1)
    pretty_lines2 = prettify(lines2)


    for line in difflib.context_diff(pretty_lines1.splitlines(), pretty_lines2.splitlines(),
                                     fromfile=args.file1, tofile=args.file2):
        print(line)
TestCmd.py 文件源码 项目:gyp 作者: electron 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def simple_diff(a, b, fromfile='', tofile='',
                    fromfiledate='', tofiledate='', n=3, lineterm='\n'):
        """
        A function with the same calling signature as difflib.context_diff
        (diff -c) and difflib.unified_diff (diff -u) but which prints
        output like the simple, unadorned 'diff" command.
        """
        sm = difflib.SequenceMatcher(None, a, b)
        def comma(x1, x2):
            return x1+1 == x2 and str(x2) or '%s,%s' % (x1+1, x2)
        result = []
        for op, a1, a2, b1, b2 in sm.get_opcodes():
            if op == 'delete':
                result.append("%sd%d" % (comma(a1, a2), b1))
                result.extend(map(lambda l: '< ' + l, a[a1:a2]))
            elif op == 'insert':
                result.append("%da%s" % (a1, comma(b1, b2)))
                result.extend(map(lambda l: '> ' + l, b[b1:b2]))
            elif op == 'replace':
                result.append("%sc%s" % (comma(a1, a2), comma(b1, b2)))
                result.extend(map(lambda l: '< ' + l, a[a1:a2]))
                result.append('---')
                result.extend(map(lambda l: '> ' + l, b[b1:b2]))
        return result
base.py 文件源码 项目:napalm-base 作者: napalm-automation 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def print_diff_strings(orig, new):
        for line in difflib.context_diff(orig.splitlines(), new.splitlines()):
            print(line)
zone-sync.py 文件源码 项目:mdb 作者: edb-gjengen 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def calculate_diff(self, new, old, zone):
        return "\n".join(context_diff(
            a=old.splitlines(),
            b=new.splitlines(),
            fromfile=str(zone.domain_active_serial) + '-' + zone.domain_name,
            tofile=str(zone.domain_serial) + '-' + zone.domain_name,
            lineterm=''))
dhcp-sync.py 文件源码 项目:mdb 作者: edb-gjengen 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def calculate_diff(self, config, new, old):
        return "\n".join(context_diff(
            a=old.splitlines(),
            b=new.splitlines(),
            fromfile=str(config.active_serial),
            tofile=str(config.serial),
            lineterm=''))
test_difflib.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_tab_delimiter(self):
        args = ['one', 'two', 'Original', 'Current',
            '2005-01-26 23:30:50', '2010-04-02 10:20:52']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], [
                           "--- Original\t2005-01-26 23:30:50",
                           "+++ Current\t2010-04-02 10:20:52"])
        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], [
                           "*** Original\t2005-01-26 23:30:50",
                           "--- Current\t2010-04-02 10:20:52"])
test_difflib.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_no_trailing_tab_on_empty_filedate(self):
        args = ['one', 'two', 'Original', 'Current']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])

        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
test_difflib.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_tab_delimiter(self):
        args = ['one', 'two', 'Original', 'Current',
            '2005-01-26 23:30:50', '2010-04-02 10:20:52']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], [
                           "--- Original\t2005-01-26 23:30:50",
                           "+++ Current\t2010-04-02 10:20:52"])
        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], [
                           "*** Original\t2005-01-26 23:30:50",
                           "--- Current\t2010-04-02 10:20:52"])
test_difflib.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_no_trailing_tab_on_empty_filedate(self):
        args = ['one', 'two', 'Original', 'Current']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])

        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
diff.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def main():

    usage = "usage: %prog [options] fromfile tofile"
    parser = optparse.OptionParser(usage)
    parser.add_option("-c", action="store_true", default=False, help='Produce a context format diff (default)')
    parser.add_option("-u", action="store_true", default=False, help='Produce a unified format diff')
    parser.add_option("-m", action="store_true", default=False, help='Produce HTML side by side diff (can use -c and -l in conjunction)')
    parser.add_option("-n", action="store_true", default=False, help='Produce a ndiff format diff')
    parser.add_option("-l", "--lines", type="int", default=3, help='Set number of context lines (default 3)')
    (options, args) = parser.parse_args()

    if len(args) == 0:
        parser.print_help()
        sys.exit(1)
    if len(args) != 2:
        parser.error("need to specify both a fromfile and tofile")

    n = options.lines
    fromfile, tofile = args

    fromdate = time.ctime(os.stat(fromfile).st_mtime)
    todate = time.ctime(os.stat(tofile).st_mtime)
    fromlines = open(fromfile, 'U').readlines()
    tolines = open(tofile, 'U').readlines()

    if options.u:
        diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
    elif options.n:
        diff = difflib.ndiff(fromlines, tolines)
    elif options.m:
        diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
    else:
        diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)

    sys.stdout.writelines(diff)
test_difflib.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_tab_delimiter(self):
        args = ['one', 'two', 'Original', 'Current',
            '2005-01-26 23:30:50', '2010-04-02 10:20:52']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], [
                           "--- Original\t2005-01-26 23:30:50",
                           "+++ Current\t2010-04-02 10:20:52"])
        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], [
                           "*** Original\t2005-01-26 23:30:50",
                           "--- Current\t2010-04-02 10:20:52"])
test_difflib.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_no_trailing_tab_on_empty_filedate(self):
        args = ['one', 'two', 'Original', 'Current']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])

        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
diff.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def main():

    usage = "usage: %prog [options] fromfile tofile"
    parser = optparse.OptionParser(usage)
    parser.add_option("-c", action="store_true", default=False, help='Produce a context format diff (default)')
    parser.add_option("-u", action="store_true", default=False, help='Produce a unified format diff')
    parser.add_option("-m", action="store_true", default=False, help='Produce HTML side by side diff (can use -c and -l in conjunction)')
    parser.add_option("-n", action="store_true", default=False, help='Produce a ndiff format diff')
    parser.add_option("-l", "--lines", type="int", default=3, help='Set number of context lines (default 3)')
    (options, args) = parser.parse_args()

    if len(args) == 0:
        parser.print_help()
        sys.exit(1)
    if len(args) != 2:
        parser.error("need to specify both a fromfile and tofile")

    n = options.lines
    fromfile, tofile = args

    fromdate = time.ctime(os.stat(fromfile).st_mtime)
    todate = time.ctime(os.stat(tofile).st_mtime)
    fromlines = open(fromfile, 'U').readlines()
    tolines = open(tofile, 'U').readlines()

    if options.u:
        diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
    elif options.n:
        diff = difflib.ndiff(fromlines, tolines)
    elif options.m:
        diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
    else:
        diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)

    sys.stdout.writelines(diff)
command.py 文件源码 项目:cli-bdd 作者: chibisov 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def step(self, output, should_not=False, exactly=False):
        child = self.get_scenario_context().command_response['child']
        ensure_command_finished(child)
        output = 'stdout' if output == 'output' else output

        # todo: separate stdout and stderr
        # todo: test replace
        data = child.logfile_read.getvalue().replace('\r\n', '\n')
        data_lines = data.splitlines()
        if data.endswith('\n'):
            data_lines.append('')

        expected = self.get_text().encode('utf-8')  # todo: test encode
        expected_lines = expected.splitlines()
        if expected.endswith('\n'):
            expected_lines.append('')

        bool_matcher = is_not if should_not else is_
        comparison_matcher = equal_to if exactly else contains_string
        try:
            assert_that(
                data,
                bool_matcher(
                    comparison_matcher(expected)
                )
            )
        except AssertionError:
            if comparison_matcher == equal_to and bool_matcher == is_:
                diff = '\n'.join(
                    difflib.context_diff(
                        data_lines,
                        expected_lines
                    )
                )
                raise AssertionError('Comparison error. Diff:\n' + diff)
            else:
                raise
test_difflib.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_tab_delimiter(self):
        args = ['one', 'two', 'Original', 'Current',
            '2005-01-26 23:30:50', '2010-04-02 10:20:52']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], [
                           "--- Original\t2005-01-26 23:30:50",
                           "+++ Current\t2010-04-02 10:20:52"])
        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], [
                           "*** Original\t2005-01-26 23:30:50",
                           "--- Current\t2010-04-02 10:20:52"])
test_difflib.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_no_trailing_tab_on_empty_filedate(self):
        args = ['one', 'two', 'Original', 'Current']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])

        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
diff.py 文件源码 项目:qal 作者: OptimalBPM 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def diff_strings(_a, _b):
    result = "---------- String A-----------\n"
    result += _a + "\n"
    result += "---------- String B-----------\n"
    result += _b + "\n"

    result += "---------- Diff between A and B-----------\n" + "\n"
    for line in difflib.context_diff(_a, _b):
        result += line

    return result
diff.py 文件源码 项目:python-fire 作者: google 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def context_diff(self, lines=3):
    return difflib.context_diff(
        self.fromlines, self.tolines, self._fromfile,
        self._tofile, self.fromdate, self.todate, n=lines)
test_difflib.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_tab_delimiter(self):
        args = ['one', 'two', 'Original', 'Current',
            '2005-01-26 23:30:50', '2010-04-02 10:20:52']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], [
                           "--- Original\t2005-01-26 23:30:50",
                           "+++ Current\t2010-04-02 10:20:52"])
        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], [
                           "*** Original\t2005-01-26 23:30:50",
                           "--- Current\t2010-04-02 10:20:52"])
test_difflib.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_no_trailing_tab_on_empty_filedate(self):
        args = ['one', 'two', 'Original', 'Current']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])

        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
test_difflib.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_tab_delimiter(self):
        args = ['one', 'two', 'Original', 'Current',
            '2005-01-26 23:30:50', '2010-04-02 10:20:52']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], [
                           "--- Original\t2005-01-26 23:30:50",
                           "+++ Current\t2010-04-02 10:20:52"])
        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], [
                           "*** Original\t2005-01-26 23:30:50",
                           "--- Current\t2010-04-02 10:20:52"])
test_difflib.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_no_trailing_tab_on_empty_filedate(self):
        args = ['one', 'two', 'Original', 'Current']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])

        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
test_difflib.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_tab_delimiter(self):
        args = ['one', 'two', 'Original', 'Current',
            '2005-01-26 23:30:50', '2010-04-02 10:20:52']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], [
                           "--- Original\t2005-01-26 23:30:50",
                           "+++ Current\t2010-04-02 10:20:52"])
        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], [
                           "*** Original\t2005-01-26 23:30:50",
                           "--- Current\t2010-04-02 10:20:52"])
test_difflib.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def test_no_trailing_tab_on_empty_filedate(self):
        args = ['one', 'two', 'Original', 'Current']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])

        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
test_difflib.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 44 收藏 0 点赞 0 评论 0
def test_tab_delimiter(self):
        args = ['one', 'two', 'Original', 'Current',
            '2005-01-26 23:30:50', '2010-04-02 10:20:52']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], [
                           "--- Original\t2005-01-26 23:30:50",
                           "+++ Current\t2010-04-02 10:20:52"])
        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], [
                           "*** Original\t2005-01-26 23:30:50",
                           "--- Current\t2010-04-02 10:20:52"])
test_difflib.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_no_trailing_tab_on_empty_filedate(self):
        args = ['one', 'two', 'Original', 'Current']
        ud = difflib.unified_diff(*args, lineterm='')
        self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])

        cd = difflib.context_diff(*args, lineterm='')
        self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
test-wd-extract.py 文件源码 项目:wikidata 作者: jimbelton 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def testSimplify(self):
        inputFile = os.path.join(wikidataDir, "data/1000.json")
        linesOut  = open(os.path.join(wikidataDir, "test/1000.out")).read().split()
        linesNew  = subprocess.check_output([wdExtractPy, "-f", "-F", "-l", "en", "-s", "", "-t", "all", inputFile]).split()
        diff      = list(difflib.context_diff(linesOut, linesNew))
        self.assertEqual(len(diff), 0, "Unexpected differences in output of wd-extract.py -f -F -l en -s '' -t all data/1000.json\n"
                                       + "".join(diff))


问题


面经


文章

微信
公众号

扫码关注公众号