本文整理汇总了Python中difflib.Differ方法的典型用法代码示例。如果您正苦于以下问题:Python difflib.Differ方法的具体用法?Python difflib.Differ怎么用?Python difflib.Differ使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类difflib
的用法示例。
在下文中一共展示了difflib.Differ方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def diff(old, new, display=True):
"""Nice colored diff implementation
"""
if not isinstance(old, list):
old = decolorize(str(old)).splitlines()
if not isinstance(new, list):
new = decolorize(str(new)).splitlines()
line_types = {' ': '%Reset', '-': '%Red', '+': '%Green', '?': '%Pink'}
if display:
for line in difflib.Differ().compare(old, new):
if line.startswith('?'):
continue
print(colorize(line_types[line[0]], line))
return old != new
示例2: assertContentsEqual
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def assertContentsEqual(self, file1, file2):
if os.path.isfile(file1):
with open(file1, 'rb') as infile:
file1 = infile.read().decode('utf-8').split('\n')
else:
file1 = file1.split('\n')
if os.path.isfile(file2):
with open(file2, 'rb') as infile:
file2 = infile.read().decode('utf-8').split('\n')
else:
file1 = file1.split('\n')
out = list(difflib.Differ().compare(file1, file2) )
print(out)
if out:
for line in out:
print(line)
raise ValueError('Files are not equal')
示例3: __init__
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def __init__(self, unexpected_method, expected):
"""Init exception.
Args:
# unexpected_method: MockMethod that was called but was not at the head of
# the expected_method queue.
# expected: MockMethod or UnorderedGroup the method should have
# been in.
unexpected_method: MockMethod
expected: MockMethod or UnorderedGroup
"""
Error.__init__(self)
if expected is None:
self._str = "Unexpected method call %s" % (unexpected_method,)
else:
differ = difflib.Differ()
diff = differ.compare(str(unexpected_method).splitlines(True),
str(expected).splitlines(True))
self._str = ("Unexpected method call. unexpected:- expected:+\n%s"
% ("\n".join(diff),))
示例4: deep_compare
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def deep_compare(actual, expected):
if type(actual) != type(expected):
return 'EXPECTED %s BUT ACTUAL %s' % (type(expected), type(actual))
elif isinstance(expected, (dict, tuple, list)):
expected_str = json.dumps(expected, indent=2, sort_keys=True)
actual_str = json.dumps(actual, indent=2, sort_keys=True)
delta = list(Differ().compare(
expected_str.splitlines(),
actual_str.splitlines()
))
if sum(1 for d in delta if d[0] in ['-', '+', '?']):
return '%s\nEXPECTED *******************************************************\n%s\nACTUAL *******************************************************\n%s' % ('\n'.join(delta), expected_str, actual_str)
elif actual != expected:
return 'EXPECTED %s != ACTUAL %s' % (expected, actual)
return None
# display results of list comparison
示例5: dicom_diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def dicom_diff(file1, file2):
""" Shows the fields that differ between two DICOM images.
Inspired by https://code.google.com/p/pydicom/source/browse/source/dicom/examples/DicomDiff.py
"""
datasets = compressed_dicom.read_file(file1), compressed_dicom.read_file(file2)
rep = []
for dataset in datasets:
lines = (str(dataset.file_meta)+"\n"+str(dataset)).split('\n')
lines = [line + '\n' for line in lines] # add the newline to the end
rep.append(lines)
diff = difflib.Differ()
for line in diff.compare(rep[0], rep[1]):
if (line[0] == '+') or (line[0] == '-'):
sys.stdout.write(line)
示例6: printerMalicious
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def printerMalicious(self, results):
differ = difflib.Differ()
for result in results:
proxy = result[1]
try:
html = requests.get("http://www.daviddworken.com/", proxies = {'http':'http://'+proxy}, headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.69 Safari/537.36'})
htmlNormal = requests.get("http://www.daviddworken.com/")
htmlHash = hashlib.sha1(html.content).digest()
htmlNormalHash = hashlib.sha1(htmlNormal.content).digest()
if(not(htmlHash == htmlNormalHash)):
htmlNormalL = htmlNormal.content.splitlines()
htmlL = html.content.splitlines()
diff = differ.compare(htmlNormalL, htmlL)
print(bcolors.WARNING + "[-] Malicious proxy found at " + proxy + bcolors.ENDC)
diffOut = '\n'.join(diff)
print(diffOut)
except:
pass
示例7: compute
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def compute():
from difflib import Differ
filename1it = fil1.get()
filename1it2 = fil2.get()
filer = open(filename1it, 'rb')
filer2 = open(filename1it2, 'rb')
data1 = filer.read()
data1 = data1.rstrip()
data2 = filer2.read()
data2 = data2.rstrip()
d = Differ()
result = list(d.compare(data1, data2))
s = "\n".join(result)
s = s.rstrip()
textbox.insert(END, "The two files compared with Difflib are " + filename1it + " and " + filename1it2 + "\n\n")
textbox.insert(END, s)
示例8: build_unified_diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def build_unified_diff(lhs_repr, rhs_repr):
differ = difflib.Differ()
lines_lhs, lines_rhs = lhs_repr.splitlines(), rhs_repr.splitlines()
diff = differ.compare(lines_lhs, lines_rhs)
output = []
for line in diff:
# Differ instructs us how to transform left into right, but we want
# our colours to indicate how to transform right into left
if line.startswith("- "):
output.append(inserted_text(" L " + line[2:]))
elif line.startswith("+ "):
output.append(deleted_text(" R " + line[2:]))
elif line.startswith("? "):
# We can use this to find the index of change in the
# line above if required in the future
pass
else:
output.append(non_formatted(line))
return output
示例9: common
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def common(self, one, two):
"""清单内容交集,不一样的地方用*号表示。
注:只是简单的匹配,可能不如人意。
Args:
one (TYPE): 第一个清单
two (TYPE): 第二个清单
Returns:
TYPE: 清单交集
"""
import difflib
from difflib import SequenceMatcher as SM
s = SM(None, one, two)
r = s.ratio()
if r == 1.0:
return one
d = difflib.Differ()
sss = ''
for item in list(d.compare(one, two)):
if item.startswith(' '):
sss += item[2:]
elif not sss.endswith('*'):
sss += '*'
return sss
示例10: check_shell
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def check_shell(self, command, expected_stdout, expected_stderr):
"""Assert output of shell command is as expected
"""
process = subprocess.Popen(command,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
process.wait()
stdout = invariant_output(process.stdout.read())
stderr = invariant_output(process.stderr.read())
stdout_diff = [dl for dl in (difflib.Differ().compare(
stdout.splitlines(),
expected_stdout.splitlines())) if not dl[0] == ' ']
stderr_diff = [dl for dl in (difflib.Differ().compare(
stderr.splitlines(),
expected_stderr.splitlines())) if not dl[0] == ' ']
self.assertEqual(remove_whitespace(str(stdout)),
remove_whitespace(str(expected_stdout)),
stdout_diff)
self.assertEqual(remove_whitespace(str(stderr)),
remove_whitespace(str(expected_stderr)),
stderr_diff)
示例11: diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def diff(str1, str2):
"""Determine if two strings differ, emit differences to stdout."""
result = list(difflib.Differ().compare(
str1.splitlines(True), str2.splitlines(True)))
same = True
for line in result:
if line[0] in ('-', '+'):
same = False
sys.stdout.write(line)
return same
示例12: main
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def main():
zk = host_utils.MysqlZookeeper()
all_sharded_systems = (list(zk.get_sharded_types()) +
environment_specific.FLEXSHARD_DBS.keys())
parser = argparse.ArgumentParser(description='MySQL schema verifier')
parser.add_argument('instance_type',
help='Type of MySQL instance to verify',
choices=all_sharded_systems)
parser.add_argument('table',
help='Table to check',)
parser.add_argument('seed_instance',
help=('Which host from which to fetch a table '
' definition. (format hostname[:port])'),)
parser.add_argument('seed_db',
help=('Which db on --seed_instance from which to fetch'
' a table definition. (ex pbdata012345)'))
args = parser.parse_args()
seed_instance = host_utils.HostAddr(args.seed_instance)
desired = mysql_lib.show_create_table(seed_instance, args.seed_db, args.table)
tbl_hash = hashlib.md5(desired).hexdigest()
print ("Desired table definition:\n{desired}").format(desired=desired)
incorrect = check_schema(args.instance_type, args.table, tbl_hash)
if len(incorrect) == 0:
print "It appears that all schema is synced"
sys.exit(0)
d = difflib.Differ()
for problem in incorrect.iteritems():
represenative = list(problem[1])[0].split(' ')
hostaddr = host_utils.HostAddr(represenative[0])
create = mysql_lib.show_create_table(hostaddr,
represenative[1],
args.table)
diff = d.compare(desired.splitlines(), create.splitlines())
print 'The following difference has been found:'
print '\n'.join(diff)
print "It is present on the following db's:"
print '\n'.join(list(problem[1]))
sys.exit(1)
示例13: test_added_tab_hint
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def test_added_tab_hint(self):
# Check fix for bug #1488943
diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
self.assertEqual("- \tI am a buggy", diff[0])
self.assertEqual("? --\n", diff[1])
self.assertEqual("+ \t\tI am a bug", diff[2])
self.assertEqual("? +\n", diff[3])
示例14: diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def diff(self, file=None, display_diff=False):
"""This function returns True is the given `file` is
a phpsploit session which differs from current session.
Otherwise, False is returned.
Additionally, if `display_diff` is set, the session
differences will be displayed in common unix `diff` style.
"""
if isinstance(file, Session):
diff = self.deepcopy(file)
else:
if file is None:
diff = Session()
diff.File = self.File
else:
diff = self.deepcopy()
diff.update(file)
diff = decolorize(diff).splitlines()
orig = decolorize(self).splitlines()
if display_diff:
color = {' ': '%Reset', '-': '%Red', '+': '%Green', '?': '%Pink'}
if file is None:
difflines = difflib.Differ().compare(diff, orig)
else:
difflines = difflib.Differ().compare(orig, diff)
for line in difflines:
# dont be too much verbose...
if line.startswith('?'):
continue
print(colorize(color[line[0]], line))
return diff != orig
示例15: black_diff
# 需要导入模块: import difflib [as 别名]
# 或者: from difflib import Differ [as 别名]
def black_diff(src: Path, differ=Differ()) -> Tuple[int, int]:
src_contents = src.read_text()
dst_contents = black.format_str(src_contents, mode=mode)
if src_contents == dst_contents:
return 0, 0
counts = Counter(
line[0]
for line in differ.compare(src_contents.splitlines(), dst_contents.splitlines())
)
return counts['+'], counts['-']