我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用difflib.context_diff()。
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)
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)
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
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)
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
def print_diff_strings(orig, new): for line in difflib.context_diff(orig.splitlines(), new.splitlines()): print(line)
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=''))
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=''))
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"])
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"])
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)
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
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
def context_diff(self, lines=3): return difflib.context_diff( self.fromlines, self.tolines, self._fromfile, self._tofile, self.fromdate, self.todate, n=lines)
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))
def diff_ast(a1, a2): for line in difflib.context_diff(repr(a1), repr(a2)): sys.stdout.write(line)
def _diff(self, baselinedir, outputdir, dc=None): if dc is None: dc = filecmp.dircmp(baselinedir, outputdir, ['.svn']) if dc.left_only: self.fail("Files or subdirectories missing from output: " +str(dc.left_only)) if dc.right_only: self.fail("Files or subdirectories missing from baseline: " +str(dc.right_only)) for name in dc.diff_files: fromfile = join(dc.left, name) tofile = join(dc.right, name) with open(fromfile, 'r') as f_from: fromlines = f_from.readlines() with open(tofile, 'r') as f_to: tolines = f_to.readlines() diff = difflib.context_diff(fromlines, tolines, fromfile+" (baseline)", tofile+" (output)") diff = list(diff) # The filecmp.dircmp function does a weaker # comparison that can sometimes lead to false # positives. Make sure the true diff is not empty # before we call this a failure. if len(diff) > 0: out = StringIO() out.write("Output file does not match baseline:\n") for line in diff: out.write(line) self.fail(out.getvalue()) for subdir in dc.subdirs: self._diff(join(baselinedir, subdir), join(outputdir, subdir), dc=dc.subdirs[subdir]) shutil.rmtree(outputdir, ignore_errors=True)
def _compare_configs(comparable_file, comparable_server, diff_output_path): if comparable_file == comparable_server: logging.info('Server config matches.') return True else: _log_and_write_config_lines( difflib.context_diff(comparable_server.split('\n'), comparable_file.split('\n')), diff_output_path) return False
def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If <BLANKLINE>s are being used, then replace blank lines # with <BLANKLINE> in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) # Check if we should use diff. if self._do_a_fancy_diff(want, got, optionflags): # Split want & got into lines. want_lines = want.splitlines(True) # True == keep line ends got_lines = got.splitlines(True) # Use difflib to find their differences. if optionflags & REPORT_UDIFF: diff = difflib.unified_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'unified diff with -expected +actual' elif optionflags & REPORT_CDIFF: diff = difflib.context_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'context diff with expected followed by actual' elif optionflags & REPORT_NDIFF: engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff = list(engine.compare(want_lines, got_lines)) kind = 'ndiff with -expected +actual' else: assert 0, 'Bad diff option' # Remove trailing whitespace on diff output. diff = [line.rstrip() + '\n' for line in diff] return 'Differences (%s):\n' % kind + _indent(''.join(diff)) # If we're not using diff, then simply list the expected # output followed by the actual output. if want and got: return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got)) elif want: return 'Expected:\n%sGot nothing\n' % _indent(want) elif got: return 'Expected nothing\nGot:\n%s' % _indent(got) else: return 'Expected nothing\nGot nothing\n'
def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If <BLANKLINE>s are being used, then replace blank lines # with <BLANKLINE> in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) # Check if we should use diff. if self._do_a_fancy_diff(want, got, optionflags): # Split want & got into lines. want_lines = want.splitlines(keepends=True) got_lines = got.splitlines(keepends=True) # Use difflib to find their differences. if optionflags & REPORT_UDIFF: diff = difflib.unified_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'unified diff with -expected +actual' elif optionflags & REPORT_CDIFF: diff = difflib.context_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'context diff with expected followed by actual' elif optionflags & REPORT_NDIFF: engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff = list(engine.compare(want_lines, got_lines)) kind = 'ndiff with -expected +actual' else: assert 0, 'Bad diff option' # Remove trailing whitespace on diff output. diff = [line.rstrip() + '\n' for line in diff] return 'Differences (%s):\n' % kind + _indent(''.join(diff)) # If we're not using diff, then simply list the expected # output followed by the actual output. if want and got: return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got)) elif want: return 'Expected:\n%sGot nothing\n' % _indent(want) elif got: return 'Expected nothing\nGot:\n%s' % _indent(got) else: return 'Expected nothing\nGot nothing\n'