本文整理汇总了Python中difflib.context_diff方法的典型用法代码示例。如果您正苦于以下问题:Python difflib.context_diff方法的具体用法?Python difflib.context_diff怎么用?Python difflib.context_diff使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类difflib
的用法示例。
在下文中一共展示了difflib.context_diff方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
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)
示例2: diff_file
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def diff_file(path1,path2,method=u'uniq',newline=True):
""" Shows difference between files
Returns the diff result (multi lines)
``path1``, ``path2`` are absolute paths.
"""
result = ""
with codecs.open(path1,'r','utf-8') as f: f1 = f.readlines()
with codecs.open(path2,'r','utf-8') as f: f2 = f.readlines()
if newline and len(f1) > 0 and len(f2) > 0:
f1[-1] = f1[-1]+'\n'
f2[-1] = f2[-1]+'\n'
diff = []
if method == 'context':
diff = difflib.context_diff(f1,f2,fromfile=path1,tofile=path2)
if method == 'uniq':
diff = difflib.ndiff(f1,f2)
result = ''.join(filter(lambda x: not x.startswith(' '),list(diff)))
BuiltIn().log("Compared `%s` and `%s`" % (path1,path2))
return result
示例3: snap_diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def snap_diff(self,name):
""" Executes the comman that have been executed before by ``name``
snapshot and return the difference.
Difference is in ``context diff`` format
"""
if not self._snap_buffer[name]: return False
cmd_list = self._snap_buffer[name]['cmd-list']
old_buffer = self._snap_buffer[name]['buffer']
buffer = ""
for cmd in cmd_list:
buffer += cmd + "\n"
buffer += self._cmd(cmd)
diff = difflib.context_diff(old_buffer.split("\n"),buffer.split("\n"),fromfile=name+":before",tofile=name+":current")
result = "\n".join(diff)
BuiltIn().log(result)
BuiltIn().log("Took snapshot `%s` and showed the difference" % name)
return result
示例4: simple_diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
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
示例5: _platform_toolchain_cmd_join
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def _platform_toolchain_cmd_join(cmds):
"""
>>> cmds = _platform_toolchain_cmd_split(test_build_template)
>>> out_template = _platform_toolchain_cmd_join(cmds)
>>> "\\n".join(difflib.context_diff("\\n".join(test_build_template), "\\n".join(out_template)))
''
>>> pprint.pprint(out_template)
['yosys -q -l {build_name}.rpt {build_name}.ys',
'nextpnr-ice40 --json {build_name}.json --pcf {build_name}.pcf',
'icepack {build_name}.txt {build_name}.bin']
"""
template = []
while len(template) < len(cmds):
for i, cmdline_parts in cmds.values():
if i != len(template):
continue
template.append(" ".join(cmdline_parts))
break
else:
raise ValueError("{} not found\n{}\n{}\n".format(len(template), template, cmds))
return template
示例6: match
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def match(self, request, recorded_request):
recorded_request = util.deserialize_prepared_request(recorded_request)
request_body = b''
if request.body:
request_body = util.coerce_content(request.body)
recorded_body = b''
if recorded_request.body:
recorded_body = util.coerce_content(recorded_request.body)
if recorded_body != request_body:
diff = difflib.context_diff(recorded_body, request_body)
log.debug('** Cassette Differences: **\n' + '\n'.join(diff))
return recorded_body == request_body
示例7: run_diff_on
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def run_diff_on(the_dict, file, tag=""):
"""
Print a context diff on 2 strings.
"""
diff = []
for key, values in the_dict.iteritems():
if tag not in key:
diff = list(difflib.context_diff(the_dict[key],
the_dict[key + tag]))
print "DIFF for {0}'s {1}:".format(key, file)
if len(diff) > 0:
pprint(diff)
else:
print "[no differences]"
print
示例8: test_mixed_types_content
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def test_mixed_types_content(self):
# type of input content must be consistent: all str or all bytes
a = [b'hello']
b = ['hello']
unified = difflib.unified_diff
context = difflib.context_diff
expect = "lines to compare must be str, not bytes (b'hello')"
self._assert_type_error(expect, unified, a, b)
self._assert_type_error(expect, unified, b, a)
self._assert_type_error(expect, context, a, b)
self._assert_type_error(expect, context, b, a)
expect = "all arguments must be bytes, not str ('hello')"
self._assert_type_error(expect, difflib.diff_bytes, unified, a, b)
self._assert_type_error(expect, difflib.diff_bytes, unified, b, a)
self._assert_type_error(expect, difflib.diff_bytes, context, a, b)
self._assert_type_error(expect, difflib.diff_bytes, context, b, a)
示例9: test_tab_delimiter
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
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"])
示例10: test_no_trailing_tab_on_empty_filedate
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
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"])
示例11: run_test
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def run_test(self, *, source, spec, expected):
qltree = qlparser.parse(source)
ir = compiler.compile_ast_to_ir(qltree, self.schema)
root = ir.scope_tree
if len(root.children) != 1:
self.fail(
f'Scope tree root is expected to have only one child, got'
f' {len(root.children)}'
f' \n{root.pformat()}'
)
scope_tree = next(iter(root.children))
path_scope = self.UUID_RE.sub(
'@SID@',
textwrap.indent(scope_tree.pformat(), ' '),
)
expected_scope = textwrap.indent(
textwrap.dedent(expected).strip(' \n'), ' ')
if path_scope != expected_scope:
diff = '\n'.join(difflib.context_diff(
expected_scope.split('\n'), path_scope.split('\n')))
self.fail(
f'Scope tree does not match the expected result.'
f'\nEXPECTED:\n{expected_scope}\nACTUAL:\n{path_scope}'
f'\nDIFF:\n{diff}')
示例12: main
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
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)
示例13: simple_diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
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.
"""
a = [to_str(q) for q in a]
b = [to_str(q) for q in b]
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(['< ' + l for l in a[a1:a2]])
elif op == 'insert':
result.append("%da%s" % (a1, comma(b1, b2)))
result.extend(['> ' + l for l in b[b1:b2]])
elif op == 'replace':
result.append("%sc%s" % (comma(a1, a2), comma(b1, b2)))
result.extend(['< ' + l for l in a[a1:a2]])
result.append('---')
result.extend(['> ' + l for l in b[b1:b2]])
return result
示例14: main
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-c', action='store_true', default=False,
help='Produce a context format diff (default)')
parser.add_argument('-u', action='store_true', default=False,
help='Produce a unified format diff')
parser.add_argument('-m', action='store_true', default=False,
help='Produce HTML side by side diff '
'(can use -c and -l in conjunction)')
parser.add_argument('-n', action='store_true', default=False,
help='Produce a ndiff format diff')
parser.add_argument('-l', '--lines', type=int, default=3,
help='Set number of context lines (default 3)')
parser.add_argument('fromfile')
parser.add_argument('tofile')
options = parser.parse_args()
n = options.lines
fromfile = options.fromfile
tofile = options.tofile
fromdate = file_mtime(fromfile)
todate = file_mtime(tofile)
with open(fromfile) as ff:
fromlines = ff.readlines()
with open(tofile) as tf:
tolines = tf.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)
示例15: verify_file_matches_repo_root
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import context_diff [as 别名]
def verify_file_matches_repo_root(result, *file, max_compare_bytes=-1):
"""
Assert that a generated file matches the one with the identical name in
the project repository root.
"""
mother_file = REPO_ROOT_PATH.join(*file).strpath
generated_file = result.project.join(*file).strpath
with open(mother_file) as mother, open(generated_file) as generated:
diff = ''.join(context_diff(mother.readlines(max_compare_bytes),
generated.readlines(max_compare_bytes),
fromfile=mother_file,
tofile=generated_file))
assert not diff, \
"Mother project '{}' not matching template.\n{}".format(
os.path.sep.join(file), diff)