summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fdifflib.html
blob: ac44dc567b6d18885b2fb2de004abb4378e1eda8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
 <span id="difflib-helpers-for-computing-deltas"></span><h1>difflib — Helpers for computing deltas</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/difflib.py">Lib/difflib.py</a></p>  <p>This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the <a class="reference internal" href="filecmp#module-filecmp" title="filecmp: Compare files efficiently."><code>filecmp</code></a> module.</p> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">difflib.</span><span class="sig-name descname">SequenceMatcher</span>
</dt> <dd>
<p>This is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a>. The basic algorithm predates, and is a little fancier than, an algorithm published in the late 1980’s by Ratcliff and Obershelp under the hyperbolic name “gestalt pattern matching.” The idea is to find the longest contiguous matching subsequence that contains no “junk” elements; these “junk” elements are ones that are uninteresting in some sense, such as blank lines or whitespace. (Handling junk is an extension to the Ratcliff and Obershelp algorithm.) The same idea is then applied recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not yield minimal edit sequences, but does tend to yield matches that “look right” to people.</p> <p><strong>Timing:</strong> The basic Ratcliff-Obershelp algorithm is cubic time in the worst case and quadratic time in the expected case. <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a> is quadratic time for the worst case and has expected-case behavior dependent in a complicated way on how many elements the sequences have in common; best case time is linear.</p> <p><strong>Automatic junk heuristic:</strong> <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a> supports a heuristic that automatically treats certain sequence items as junk. The heuristic counts how many times each individual item appears in the sequence. If an item’s duplicates (after the first one) account for more than 1% of the sequence and the sequence is at least 200 items long, this item is marked as “popular” and is treated as junk for the purpose of sequence matching. This heuristic can be turned off by setting the <code>autojunk</code> argument to <code>False</code> when creating the <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>The <em>autojunk</em> parameter.</p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="difflib.Differ">
<code>class difflib.Differ</code> </dt> <dd>
<p>This is a class for comparing sequences of lines of text, and producing human-readable differences or deltas. Differ uses <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a> both to compare sequences of lines, and to compare sequences of characters within similar (near-matching) lines.</p> <p>Each line of a <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code>Differ</code></a> delta begins with a two-letter code:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Code</p></th> <th class="head"><p>Meaning</p></th> </tr> </thead>  <tr>
<td><p><code>'- '</code></p></td> <td><p>line unique to sequence 1</p></td> </tr> <tr>
<td><p><code>'+ '</code></p></td> <td><p>line unique to sequence 2</p></td> </tr> <tr>
<td><p><code>'  '</code></p></td> <td><p>line common to both sequences</p></td> </tr> <tr>
<td><p><code>'? '</code></p></td> <td><p>line not present in either input sequence</p></td> </tr>  </table> <p>Lines beginning with ‘<code>?</code>’ attempt to guide the eye to intraline differences, and were not present in either input sequence. These lines can be confusing if the sequences contain whitespace characters, such as spaces, tabs or line breaks.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="difflib.HtmlDiff">
<code>class difflib.HtmlDiff</code> </dt> <dd>
<p>This class can be used to create an HTML table (or a complete HTML file containing the table) showing a side by side, line by line comparison of text with inter-line and intra-line change highlights. The table can be generated in either full or contextual difference mode.</p> <p>The constructor for this class is:</p> <dl class="py method"> <dt class="sig sig-object py" id="difflib.HtmlDiff.__init__">
<code>__init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)</code> </dt> <dd>
<p>Initializes instance of <a class="reference internal" href="#difflib.HtmlDiff" title="difflib.HtmlDiff"><code>HtmlDiff</code></a>.</p> <p><em>tabsize</em> is an optional keyword argument to specify tab stop spacing and defaults to <code>8</code>.</p> <p><em>wrapcolumn</em> is an optional keyword to specify column number where lines are broken and wrapped, defaults to <code>None</code> where lines are not wrapped.</p> <p><em>linejunk</em> and <em>charjunk</em> are optional keyword arguments passed into <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code>ndiff()</code></a> (used by <a class="reference internal" href="#difflib.HtmlDiff" title="difflib.HtmlDiff"><code>HtmlDiff</code></a> to generate the side by side HTML differences). See <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code>ndiff()</code></a> documentation for argument default values and descriptions.</p> </dd>
</dl> <p>The following methods are public:</p> <dl class="py method"> <dt class="sig sig-object py" id="difflib.HtmlDiff.make_file">
<code>make_file(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5, *, charset='utf-8')</code> </dt> <dd>
<p>Compares <em>fromlines</em> and <em>tolines</em> (lists of strings) and returns a string which is a complete HTML file containing a table showing line by line differences with inter-line and intra-line changes highlighted.</p> <p><em>fromdesc</em> and <em>todesc</em> are optional keyword arguments to specify from/to file column header strings (both default to an empty string).</p> <p><em>context</em> and <em>numlines</em> are both optional keyword arguments. Set <em>context</em> to <code>True</code> when contextual differences are to be shown, else the default is <code>False</code> to show the full files. <em>numlines</em> defaults to <code>5</code>. When <em>context</em> is <code>True</code> <em>numlines</em> controls the number of context lines which surround the difference highlights. When <em>context</em> is <code>False</code> <em>numlines</em> controls the number of lines which are shown before a difference highlight when using the “next” hyperlinks (setting to zero would cause the “next” hyperlinks to place the next difference highlight at the top of the browser without any leading context).</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><em>fromdesc</em> and <em>todesc</em> are interpreted as unescaped HTML and should be properly escaped while receiving input from untrusted sources.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span><em>charset</em> keyword-only argument was added. The default charset of HTML document changed from <code>'ISO-8859-1'</code> to <code>'utf-8'</code>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.HtmlDiff.make_table">
<code>make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5)</code> </dt> <dd>
<p>Compares <em>fromlines</em> and <em>tolines</em> (lists of strings) and returns a string which is a complete HTML table showing line by line differences with inter-line and intra-line changes highlighted.</p> <p>The arguments for this method are the same as those for the <a class="reference internal" href="#difflib.HtmlDiff.make_file" title="difflib.HtmlDiff.make_file"><code>make_file()</code></a> method.</p> </dd>
</dl> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="difflib.context_diff">
<code>difflib.context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')</code> </dt> <dd>
<p>Compare <em>a</em> and <em>b</em> (lists of strings); return a delta (a <a class="reference internal" href="../glossary#term-generator"><span class="xref std std-term">generator</span></a> generating the delta lines) in context diff format.</p> <p>Context diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in a before/after style. The number of context lines is set by <em>n</em> which defaults to three.</p> <p>By default, the diff control lines (those with <code>***</code> or <code>---</code>) are created with a trailing newline. This is helpful so that inputs created from <a class="reference internal" href="io#io.IOBase.readlines" title="io.IOBase.readlines"><code>io.IOBase.readlines()</code></a> result in diffs that are suitable for use with <a class="reference internal" href="io#io.IOBase.writelines" title="io.IOBase.writelines"><code>io.IOBase.writelines()</code></a> since both the inputs and outputs have trailing newlines.</p> <p>For inputs that do not have trailing newlines, set the <em>lineterm</em> argument to <code>""</code> so that the output will be uniformly newline free.</p> <p>The context diff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for <em>fromfile</em>, <em>tofile</em>, <em>fromfiledate</em>, and <em>tofiledate</em>. The modification times are normally expressed in the ISO 8601 format. If not specified, the strings default to blanks.</p> <pre data-language="python">&gt;&gt;&gt; import sys
&gt;&gt;&gt; from difflib import *
&gt;&gt;&gt; s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
&gt;&gt;&gt; s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
&gt;&gt;&gt; sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py',
...                        tofile='after.py'))
*** before.py
--- after.py
***************
*** 1,4 ****
! bacon
! eggs
! ham
  guido
--- 1,4 ----
! python
! eggy
! hamster
  guido
</pre> <p>See <a class="reference internal" href="#difflib-interface"><span class="std std-ref">A command-line interface to difflib</span></a> for a more detailed example.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="difflib.get_close_matches">
<code>difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6)</code> </dt> <dd>
<p>Return a list of the best “good enough” matches. <em>word</em> is a sequence for which close matches are desired (typically a string), and <em>possibilities</em> is a list of sequences against which to match <em>word</em> (typically a list of strings).</p> <p>Optional argument <em>n</em> (default <code>3</code>) is the maximum number of close matches to return; <em>n</em> must be greater than <code>0</code>.</p> <p>Optional argument <em>cutoff</em> (default <code>0.6</code>) is a float in the range [0, 1]. Possibilities that don’t score at least that similar to <em>word</em> are ignored.</p> <p>The best (no more than <em>n</em>) matches among the possibilities are returned in a list, sorted by similarity score, most similar first.</p> <pre data-language="python">&gt;&gt;&gt; get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
&gt;&gt;&gt; import keyword
&gt;&gt;&gt; get_close_matches('wheel', keyword.kwlist)
['while']
&gt;&gt;&gt; get_close_matches('pineapple', keyword.kwlist)
[]
&gt;&gt;&gt; get_close_matches('accept', keyword.kwlist)
['except']
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="difflib.ndiff">
<code>difflib.ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)</code> </dt> <dd>
<p>Compare <em>a</em> and <em>b</em> (lists of strings); return a <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code>Differ</code></a>-style delta (a <a class="reference internal" href="../glossary#term-generator"><span class="xref std std-term">generator</span></a> generating the delta lines).</p> <p>Optional keyword parameters <em>linejunk</em> and <em>charjunk</em> are filtering functions (or <code>None</code>):</p> <p><em>linejunk</em>: A function that accepts a single string argument, and returns true if the string is junk, or false if not. The default is <code>None</code>. There is also a module-level function <a class="reference internal" href="#difflib.IS_LINE_JUNK" title="difflib.IS_LINE_JUNK"><code>IS_LINE_JUNK()</code></a>, which filters out lines without visible characters, except for at most one pound character (<code>'#'</code>) – however the underlying <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a> class does a dynamic analysis of which lines are so frequent as to constitute noise, and this usually works better than using this function.</p> <p><em>charjunk</em>: A function that accepts a character (a string of length 1), and returns if the character is junk, or false if not. The default is module-level function <a class="reference internal" href="#difflib.IS_CHARACTER_JUNK" title="difflib.IS_CHARACTER_JUNK"><code>IS_CHARACTER_JUNK()</code></a>, which filters out whitespace characters (a blank or tab; it’s a bad idea to include newline in this!).</p> <pre data-language="python">&gt;&gt;&gt; diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
...              'ore\ntree\nemu\n'.splitlines(keepends=True))
&gt;&gt;&gt; print(''.join(diff), end="")
- one
?  ^
+ ore
?  ^
- two
- three
?  -
+ tree
+ emu
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="difflib.restore">
<code>difflib.restore(sequence, which)</code> </dt> <dd>
<p>Return one of the two sequences that generated a delta.</p> <p>Given a <em>sequence</em> produced by <a class="reference internal" href="#difflib.Differ.compare" title="difflib.Differ.compare"><code>Differ.compare()</code></a> or <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code>ndiff()</code></a>, extract lines originating from file 1 or 2 (parameter <em>which</em>), stripping off line prefixes.</p> <p>Example:</p> <pre data-language="python">&gt;&gt;&gt; diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
...              'ore\ntree\nemu\n'.splitlines(keepends=True))
&gt;&gt;&gt; diff = list(diff) # materialize the generated delta into a list
&gt;&gt;&gt; print(''.join(restore(diff, 1)), end="")
one
two
three
&gt;&gt;&gt; print(''.join(restore(diff, 2)), end="")
ore
tree
emu
</pre> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="difflib.unified_diff">
<code>difflib.unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')</code> </dt> <dd>
<p>Compare <em>a</em> and <em>b</em> (lists of strings); return a delta (a <a class="reference internal" href="../glossary#term-generator"><span class="xref std std-term">generator</span></a> generating the delta lines) in unified diff format.</p> <p>Unified diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in an inline style (instead of separate before/after blocks). The number of context lines is set by <em>n</em> which defaults to three.</p> <p>By default, the diff control lines (those with <code>---</code>, <code>+++</code>, or <code>@@</code>) are created with a trailing newline. This is helpful so that inputs created from <a class="reference internal" href="io#io.IOBase.readlines" title="io.IOBase.readlines"><code>io.IOBase.readlines()</code></a> result in diffs that are suitable for use with <a class="reference internal" href="io#io.IOBase.writelines" title="io.IOBase.writelines"><code>io.IOBase.writelines()</code></a> since both the inputs and outputs have trailing newlines.</p> <p>For inputs that do not have trailing newlines, set the <em>lineterm</em> argument to <code>""</code> so that the output will be uniformly newline free.</p> <p>The unified diff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for <em>fromfile</em>, <em>tofile</em>, <em>fromfiledate</em>, and <em>tofiledate</em>. The modification times are normally expressed in the ISO 8601 format. If not specified, the strings default to blanks.</p> <pre data-language="python">&gt;&gt;&gt; s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
&gt;&gt;&gt; s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
&gt;&gt;&gt; sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py'))
--- before.py
+++ after.py
@@ -1,4 +1,4 @@
-bacon
-eggs
-ham
+python
+eggy
+hamster
 guido
</pre> <p>See <a class="reference internal" href="#difflib-interface"><span class="std std-ref">A command-line interface to difflib</span></a> for a more detailed example.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="difflib.diff_bytes">
<code>difflib.diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n')</code> </dt> <dd>
<p>Compare <em>a</em> and <em>b</em> (lists of bytes objects) using <em>dfunc</em>; yield a sequence of delta lines (also bytes) in the format returned by <em>dfunc</em>. <em>dfunc</em> must be a callable, typically either <a class="reference internal" href="#difflib.unified_diff" title="difflib.unified_diff"><code>unified_diff()</code></a> or <a class="reference internal" href="#difflib.context_diff" title="difflib.context_diff"><code>context_diff()</code></a>.</p> <p>Allows you to compare data with unknown or inconsistent encoding. All inputs except <em>n</em> must be bytes objects, not str. Works by losslessly converting all inputs (except <em>n</em>) to str, and calling <code>dfunc(a, b,
fromfile, tofile, fromfiledate, tofiledate, n, lineterm)</code>. The output of <em>dfunc</em> is then converted back to bytes, so the delta lines that you receive have the same unknown/inconsistent encodings as <em>a</em> and <em>b</em>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="difflib.IS_LINE_JUNK">
<code>difflib.IS_LINE_JUNK(line)</code> </dt> <dd>
<p>Return <code>True</code> for ignorable lines. The line <em>line</em> is ignorable if <em>line</em> is blank or contains a single <code>'#'</code>, otherwise it is not ignorable. Used as a default for parameter <em>linejunk</em> in <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code>ndiff()</code></a> in older versions.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="difflib.IS_CHARACTER_JUNK">
<code>difflib.IS_CHARACTER_JUNK(ch)</code> </dt> <dd>
<p>Return <code>True</code> for ignorable characters. The character <em>ch</em> is ignorable if <em>ch</em> is a space or tab, otherwise it is not ignorable. Used as a default for parameter <em>charjunk</em> in <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code>ndiff()</code></a>.</p> </dd>
</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference external" href="https://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970">Pattern Matching: The Gestalt Approach</a></dt>
<dd>
<p>Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This was published in <a class="reference external" href="https://www.drdobbs.com/">Dr. Dobb’s Journal</a> in July, 1988.</p> </dd> </dl> </div> <section id="sequencematcher-objects"> <span id="sequence-matcher"></span><h2>SequenceMatcher Objects</h2> <p>The <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a> class has this constructor:</p> <dl class="py class"> <dt class="sig sig-object py" id="difflib.SequenceMatcher">
<code>class difflib.SequenceMatcher(isjunk=None, a='', b='', autojunk=True)</code> </dt> <dd>
<p>Optional argument <em>isjunk</em> must be <code>None</code> (the default) or a one-argument function that takes a sequence element and returns true if and only if the element is “junk” and should be ignored. Passing <code>None</code> for <em>isjunk</em> is equivalent to passing <code>lambda x: False</code>; in other words, no elements are ignored. For example, pass:</p> <pre data-language="python">lambda x: x in " \t"
</pre> <p>if you’re comparing lines as sequences of characters, and don’t want to synch up on blanks or hard tabs.</p> <p>The optional arguments <em>a</em> and <em>b</em> are sequences to be compared; both default to empty strings. The elements of both sequences must be <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a>.</p> <p>The optional argument <em>autojunk</em> can be used to disable the automatic junk heuristic.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>The <em>autojunk</em> parameter.</p> </div> <p>SequenceMatcher objects get three data attributes: <em>bjunk</em> is the set of elements of <em>b</em> for which <em>isjunk</em> is <code>True</code>; <em>bpopular</em> is the set of non-junk elements considered popular by the heuristic (if it is not disabled); <em>b2j</em> is a dict mapping the remaining elements of <em>b</em> to a list of positions where they occur. All three are reset whenever <em>b</em> is reset with <a class="reference internal" href="#difflib.SequenceMatcher.set_seqs" title="difflib.SequenceMatcher.set_seqs"><code>set_seqs()</code></a> or <a class="reference internal" href="#difflib.SequenceMatcher.set_seq2" title="difflib.SequenceMatcher.set_seq2"><code>set_seq2()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>The <em>bjunk</em> and <em>bpopular</em> attributes.</p> </div> <p><a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a> objects have the following methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.set_seqs">
<code>set_seqs(a, b)</code> </dt> <dd>
<p>Set the two sequences to be compared.</p> </dd>
</dl> <p><a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a> computes and caches detailed information about the second sequence, so if you want to compare one sequence against many sequences, use <a class="reference internal" href="#difflib.SequenceMatcher.set_seq2" title="difflib.SequenceMatcher.set_seq2"><code>set_seq2()</code></a> to set the commonly used sequence once and call <a class="reference internal" href="#difflib.SequenceMatcher.set_seq1" title="difflib.SequenceMatcher.set_seq1"><code>set_seq1()</code></a> repeatedly, once for each of the other sequences.</p> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.set_seq1">
<code>set_seq1(a)</code> </dt> <dd>
<p>Set the first sequence to be compared. The second sequence to be compared is not changed.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.set_seq2">
<code>set_seq2(b)</code> </dt> <dd>
<p>Set the second sequence to be compared. The first sequence to be compared is not changed.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.find_longest_match">
<code>find_longest_match(alo=0, ahi=None, blo=0, bhi=None)</code> </dt> <dd>
<p>Find longest matching block in <code>a[alo:ahi]</code> and <code>b[blo:bhi]</code>.</p> <p>If <em>isjunk</em> was omitted or <code>None</code>, <a class="reference internal" href="#difflib.SequenceMatcher.find_longest_match" title="difflib.SequenceMatcher.find_longest_match"><code>find_longest_match()</code></a> returns <code>(i, j, k)</code> such that <code>a[i:i+k]</code> is equal to <code>b[j:j+k]</code>, where <code>alo
&lt;= i &lt;= i+k &lt;= ahi</code> and <code>blo &lt;= j &lt;= j+k &lt;= bhi</code>. For all <code>(i', j',
k')</code> meeting those conditions, the additional conditions <code>k &gt;= k'</code>, <code>i
&lt;= i'</code>, and if <code>i == i'</code>, <code>j &lt;= j'</code> are also met. In other words, of all maximal matching blocks, return one that starts earliest in <em>a</em>, and of all those maximal matching blocks that start earliest in <em>a</em>, return the one that starts earliest in <em>b</em>.</p> <pre data-language="python">&gt;&gt;&gt; s = SequenceMatcher(None, " abcd", "abcd abcd")
&gt;&gt;&gt; s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
</pre> <p>If <em>isjunk</em> was provided, first the longest matching block is determined as above, but with the additional restriction that no junk element appears in the block. Then that block is extended as far as possible by matching (only) junk elements on both sides. So the resulting block never matches on junk except as identical junk happens to be adjacent to an interesting match.</p> <p>Here’s the same example as before, but considering blanks to be junk. That prevents <code>' abcd'</code> from matching the <code>' abcd'</code> at the tail end of the second sequence directly. Instead only the <code>'abcd'</code> can match, and matches the leftmost <code>'abcd'</code> in the second sequence:</p> <pre data-language="python">&gt;&gt;&gt; s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
&gt;&gt;&gt; s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
</pre> <p>If no blocks match, this returns <code>(alo, blo, 0)</code>.</p> <p>This method returns a <a class="reference internal" href="../glossary#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code>Match(a, b, size)</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added default arguments.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.get_matching_blocks">
<code>get_matching_blocks()</code> </dt> <dd>
<p>Return list of triples describing non-overlapping matching subsequences. Each triple is of the form <code>(i, j, n)</code>, and means that <code>a[i:i+n] == b[j:j+n]</code>. The triples are monotonically increasing in <em>i</em> and <em>j</em>.</p> <p>The last triple is a dummy, and has the value <code>(len(a), len(b), 0)</code>. It is the only triple with <code>n == 0</code>. If <code>(i, j, n)</code> and <code>(i', j', n')</code> are adjacent triples in the list, and the second is not the last triple in the list, then <code>i+n &lt; i'</code> or <code>j+n &lt; j'</code>; in other words, adjacent triples always describe non-adjacent equal blocks.</p> <pre data-language="pycon3">&gt;&gt;&gt; s = SequenceMatcher(None, "abxcd", "abcd")
&gt;&gt;&gt; s.get_matching_blocks()
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.get_opcodes">
<code>get_opcodes()</code> </dt> <dd>
<p>Return list of 5-tuples describing how to turn <em>a</em> into <em>b</em>. Each tuple is of the form <code>(tag, i1, i2, j1, j2)</code>. The first tuple has <code>i1 == j1 ==
0</code>, and remaining tuples have <em>i1</em> equal to the <em>i2</em> from the preceding tuple, and, likewise, <em>j1</em> equal to the previous <em>j2</em>.</p> <p>The <em>tag</em> values are strings, with these meanings:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Value</p></th> <th class="head"><p>Meaning</p></th> </tr> </thead>  <tr>
<td><p><code>'replace'</code></p></td> <td><p><code>a[i1:i2]</code> should be replaced by <code>b[j1:j2]</code>.</p></td> </tr> <tr>
<td><p><code>'delete'</code></p></td> <td><p><code>a[i1:i2]</code> should be deleted. Note that <code>j1 == j2</code> in this case.</p></td> </tr> <tr>
<td><p><code>'insert'</code></p></td> <td><p><code>b[j1:j2]</code> should be inserted at <code>a[i1:i1]</code>. Note that <code>i1 == i2</code> in this case.</p></td> </tr> <tr>
<td><p><code>'equal'</code></p></td> <td><p><code>a[i1:i2] == b[j1:j2]</code> (the sub-sequences are equal).</p></td> </tr>  </table> <p>For example:</p> <pre data-language="python">&gt;&gt;&gt; a = "qabxcd"
&gt;&gt;&gt; b = "abycdf"
&gt;&gt;&gt; s = SequenceMatcher(None, a, b)
&gt;&gt;&gt; for tag, i1, i2, j1, j2 in s.get_opcodes():
...     print('{:7}   a[{}:{}] --&gt; b[{}:{}] {!r:&gt;8} --&gt; {!r}'.format(
...         tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
delete    a[0:1] --&gt; b[0:0]      'q' --&gt; ''
equal     a[1:3] --&gt; b[0:2]     'ab' --&gt; 'ab'
replace   a[3:4] --&gt; b[2:3]      'x' --&gt; 'y'
equal     a[4:6] --&gt; b[3:5]     'cd' --&gt; 'cd'
insert    a[6:6] --&gt; b[5:6]       '' --&gt; 'f'
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.get_grouped_opcodes">
<code>get_grouped_opcodes(n=3)</code> </dt> <dd>
<p>Return a <a class="reference internal" href="../glossary#term-generator"><span class="xref std std-term">generator</span></a> of groups with up to <em>n</em> lines of context.</p> <p>Starting with the groups returned by <a class="reference internal" href="#difflib.SequenceMatcher.get_opcodes" title="difflib.SequenceMatcher.get_opcodes"><code>get_opcodes()</code></a>, this method splits out smaller change clusters and eliminates intervening ranges which have no changes.</p> <p>The groups are returned in the same format as <a class="reference internal" href="#difflib.SequenceMatcher.get_opcodes" title="difflib.SequenceMatcher.get_opcodes"><code>get_opcodes()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.ratio">
<code>ratio()</code> </dt> <dd>
<p>Return a measure of the sequences’ similarity as a float in the range [0, 1].</p> <p>Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. Note that this is <code>1.0</code> if the sequences are identical, and <code>0.0</code> if they have nothing in common.</p> <p>This is expensive to compute if <a class="reference internal" href="#difflib.SequenceMatcher.get_matching_blocks" title="difflib.SequenceMatcher.get_matching_blocks"><code>get_matching_blocks()</code></a> or <a class="reference internal" href="#difflib.SequenceMatcher.get_opcodes" title="difflib.SequenceMatcher.get_opcodes"><code>get_opcodes()</code></a> hasn’t already been called, in which case you may want to try <a class="reference internal" href="#difflib.SequenceMatcher.quick_ratio" title="difflib.SequenceMatcher.quick_ratio"><code>quick_ratio()</code></a> or <a class="reference internal" href="#difflib.SequenceMatcher.real_quick_ratio" title="difflib.SequenceMatcher.real_quick_ratio"><code>real_quick_ratio()</code></a> first to get an upper bound.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Caution: The result of a <a class="reference internal" href="#difflib.SequenceMatcher.ratio" title="difflib.SequenceMatcher.ratio"><code>ratio()</code></a> call may depend on the order of the arguments. For instance:</p> <pre data-language="python">&gt;&gt;&gt; SequenceMatcher(None, 'tide', 'diet').ratio()
0.25
&gt;&gt;&gt; SequenceMatcher(None, 'diet', 'tide').ratio()
0.5
</pre> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.quick_ratio">
<code>quick_ratio()</code> </dt> <dd>
<p>Return an upper bound on <a class="reference internal" href="#difflib.SequenceMatcher.ratio" title="difflib.SequenceMatcher.ratio"><code>ratio()</code></a> relatively quickly.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="difflib.SequenceMatcher.real_quick_ratio">
<code>real_quick_ratio()</code> </dt> <dd>
<p>Return an upper bound on <a class="reference internal" href="#difflib.SequenceMatcher.ratio" title="difflib.SequenceMatcher.ratio"><code>ratio()</code></a> very quickly.</p> </dd>
</dl> </dd>
</dl> <p>The three methods that return the ratio of matching to total characters can give different results due to differing levels of approximation, although <a class="reference internal" href="#difflib.SequenceMatcher.quick_ratio" title="difflib.SequenceMatcher.quick_ratio"><code>quick_ratio()</code></a> and <a class="reference internal" href="#difflib.SequenceMatcher.real_quick_ratio" title="difflib.SequenceMatcher.real_quick_ratio"><code>real_quick_ratio()</code></a> are always at least as large as <a class="reference internal" href="#difflib.SequenceMatcher.ratio" title="difflib.SequenceMatcher.ratio"><code>ratio()</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; s = SequenceMatcher(None, "abcd", "bcde")
&gt;&gt;&gt; s.ratio()
0.75
&gt;&gt;&gt; s.quick_ratio()
0.75
&gt;&gt;&gt; s.real_quick_ratio()
1.0
</pre> </section> <section id="sequencematcher-examples"> <span id="id1"></span><h2>SequenceMatcher Examples</h2> <p>This example compares two strings, considering blanks to be “junk”:</p> <pre data-language="python">&gt;&gt;&gt; s = SequenceMatcher(lambda x: x == " ",
...                     "private Thread currentThread;",
...                     "private volatile Thread currentThread;")
</pre> <p><a class="reference internal" href="#difflib.SequenceMatcher.ratio" title="difflib.SequenceMatcher.ratio"><code>ratio()</code></a> returns a float in [0, 1], measuring the similarity of the sequences. As a rule of thumb, a <a class="reference internal" href="#difflib.SequenceMatcher.ratio" title="difflib.SequenceMatcher.ratio"><code>ratio()</code></a> value over 0.6 means the sequences are close matches:</p> <pre data-language="python">&gt;&gt;&gt; print(round(s.ratio(), 3))
0.866
</pre> <p>If you’re only interested in where the sequences match, <a class="reference internal" href="#difflib.SequenceMatcher.get_matching_blocks" title="difflib.SequenceMatcher.get_matching_blocks"><code>get_matching_blocks()</code></a> is handy:</p> <pre data-language="python">&gt;&gt;&gt; for block in s.get_matching_blocks():
...     print("a[%d] and b[%d] match for %d elements" % block)
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements
</pre> <p>Note that the last tuple returned by <a class="reference internal" href="#difflib.SequenceMatcher.get_matching_blocks" title="difflib.SequenceMatcher.get_matching_blocks"><code>get_matching_blocks()</code></a> is always a dummy, <code>(len(a), len(b), 0)</code>, and this is the only case in which the last tuple element (number of elements matched) is <code>0</code>.</p> <p>If you want to know how to change the first sequence into the second, use <a class="reference internal" href="#difflib.SequenceMatcher.get_opcodes" title="difflib.SequenceMatcher.get_opcodes"><code>get_opcodes()</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; for opcode in s.get_opcodes():
...     print("%6s a[%d:%d] b[%d:%d]" % opcode)
 equal a[0:8] b[0:8]
insert a[8:8] b[8:17]
 equal a[8:29] b[17:38]
</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li>The <a class="reference internal" href="#difflib.get_close_matches" title="difflib.get_close_matches"><code>get_close_matches()</code></a> function in this module which shows how simple code building on <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a> can be used to do useful work.</li> <li>
<a class="reference external" href="https://code.activestate.com/recipes/576729/">Simple version control recipe</a> for a small application built with <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code>SequenceMatcher</code></a>.</li> </ul> </div> </section> <section id="differ-objects"> <span id="id2"></span><h2>Differ Objects</h2> <p>Note that <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code>Differ</code></a>-generated deltas make no claim to be <strong>minimal</strong> diffs. To the contrary, minimal diffs are often counter-intuitive, because they synch up anywhere possible, sometimes accidental matches 100 pages apart. Restricting synch points to contiguous matches preserves some notion of locality, at the occasional cost of producing a longer diff.</p> <p>The <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code>Differ</code></a> class has this constructor:</p> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">difflib.</span><span class="sig-name descname">Differ</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">linejunk</span><span class="o">=</span><span class="default_value">None</span></em>, <em class="sig-param"><span class="n">charjunk</span><span class="o">=</span><span class="default_value">None</span></em><span class="sig-paren">)</span>
</dt> <dd>
<p>Optional keyword parameters <em>linejunk</em> and <em>charjunk</em> are for filter functions (or <code>None</code>):</p> <p><em>linejunk</em>: A function that accepts a single string argument, and returns true if the string is junk. The default is <code>None</code>, meaning that no line is considered junk.</p> <p><em>charjunk</em>: A function that accepts a single character argument (a string of length 1), and returns true if the character is junk. The default is <code>None</code>, meaning that no character is considered junk.</p> <p>These junk-filtering functions speed up matching to find differences and do not cause any differing lines or characters to be ignored. Read the description of the <a class="reference internal" href="#difflib.SequenceMatcher.find_longest_match" title="difflib.SequenceMatcher.find_longest_match"><code>find_longest_match()</code></a> method’s <em>isjunk</em> parameter for an explanation.</p> <p><a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code>Differ</code></a> objects are used (deltas generated) via a single method:</p> <dl class="py method"> <dt class="sig sig-object py" id="difflib.Differ.compare">
<code>compare(a, b)</code> </dt> <dd>
<p>Compare two sequences of lines, and generate the delta (a sequence of lines).</p> <p>Each sequence must contain individual single-line strings ending with newlines. Such sequences can be obtained from the <a class="reference internal" href="io#io.IOBase.readlines" title="io.IOBase.readlines"><code>readlines()</code></a> method of file-like objects. The delta generated also consists of newline-terminated strings, ready to be printed as-is via the <a class="reference internal" href="io#io.IOBase.writelines" title="io.IOBase.writelines"><code>writelines()</code></a> method of a file-like object.</p> </dd>
</dl> </dd>
</dl> </section> <section id="differ-example"> <span id="differ-examples"></span><h2>Differ Example</h2> <p>This example compares two texts. First we set up the texts, sequences of individual single-line strings ending with newlines (such sequences can also be obtained from the <a class="reference internal" href="io#io.IOBase.readlines" title="io.IOBase.readlines"><code>readlines()</code></a> method of file-like objects):</p> <pre data-language="python">&gt;&gt;&gt; text1 = '''  1. Beautiful is better than ugly.
...   2. Explicit is better than implicit.
...   3. Simple is better than complex.
...   4. Complex is better than complicated.
... '''.splitlines(keepends=True)
&gt;&gt;&gt; len(text1)
4
&gt;&gt;&gt; text1[0][-1]
'\n'
&gt;&gt;&gt; text2 = '''  1. Beautiful is better than ugly.
...   3.   Simple is better than complex.
...   4. Complicated is better than complex.
...   5. Flat is better than nested.
... '''.splitlines(keepends=True)
</pre> <p>Next we instantiate a Differ object:</p> <pre data-language="python">&gt;&gt;&gt; d = Differ()
</pre> <p>Note that when instantiating a <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code>Differ</code></a> object we may pass functions to filter out line and character “junk.” See the <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code>Differ()</code></a> constructor for details.</p> <p>Finally, we compare the two:</p> <pre data-language="python">&gt;&gt;&gt; result = list(d.compare(text1, text2))
</pre> <p><code>result</code> is a list of strings, so let’s pretty-print it:</p> <pre data-language="python">&gt;&gt;&gt; from pprint import pprint
&gt;&gt;&gt; pprint(result)
['    1. Beautiful is better than ugly.\n',
 '-   2. Explicit is better than implicit.\n',
 '-   3. Simple is better than complex.\n',
 '+   3.   Simple is better than complex.\n',
 '?     ++\n',
 '-   4. Complex is better than complicated.\n',
 '?            ^                     ---- ^\n',
 '+   4. Complicated is better than complex.\n',
 '?           ++++ ^                      ^\n',
 '+   5. Flat is better than nested.\n']
</pre> <p>As a single multi-line string it looks like this:</p> <pre data-language="python">&gt;&gt;&gt; import sys
&gt;&gt;&gt; sys.stdout.writelines(result)
    1. Beautiful is better than ugly.
-   2. Explicit is better than implicit.
-   3. Simple is better than complex.
+   3.   Simple is better than complex.
?     ++
-   4. Complex is better than complicated.
?            ^                     ---- ^
+   4. Complicated is better than complex.
?           ++++ ^                      ^
+   5. Flat is better than nested.
</pre> </section> <section id="a-command-line-interface-to-difflib"> <span id="difflib-interface"></span><h2>A command-line interface to difflib</h2> <p>This example shows how to use difflib to create a <code>diff</code>-like utility.</p> <pre data-language="python">""" Command line interface to difflib.py providing diffs in four formats:

* ndiff:    lists every line and highlights interline changes.
* context:  highlights clusters of changes in a before/after format.
* unified:  highlights clusters of changes in an inline format.
* html:     generates side by side comparison with change highlights.

"""

import sys, os, difflib, argparse
from datetime import datetime, timezone

def file_mtime(path):
    t = datetime.fromtimestamp(os.stat(path).st_mtime,
                               timezone.utc)
    return t.astimezone().isoformat()

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)

if __name__ == '__main__':
    main()
</pre> </section> <section id="ndiff-example"> <h2>ndiff example</h2> <p>This example shows how to use <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code>difflib.ndiff()</code></a>.</p> <pre data-language="python">"""ndiff [-q] file1 file2
    or
ndiff (-r1 | -r2) &lt; ndiff_output &gt; file1_or_file2

Print a human-friendly file difference report to stdout.  Both inter-
and intra-line differences are noted.  In the second form, recreate file1
(-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.

In the first form, if -q ("quiet") is not specified, the first two lines
of output are

-: file1
+: file2

Each remaining line begins with a two-letter code:

    "- "    line unique to file1
    "+ "    line unique to file2
    "  "    line common to both files
    "? "    line not present in either input file

Lines beginning with "? " attempt to guide the eye to intraline
differences, and were not present in either input file.  These lines can be
confusing if the source files contain tab characters.

The first file can be recovered by retaining only lines that begin with
"  " or "- ", and deleting those 2-character prefixes; use ndiff with -r1.

The second file can be recovered similarly, but by retaining only "  " and
"+ " lines; use ndiff with -r2; or, on Unix, the second file can be
recovered by piping the output through

    sed -n '/^[+ ] /s/^..//p'
"""

__version__ = 1, 7, 0

import difflib, sys

def fail(msg):
    out = sys.stderr.write
    out(msg + "\n\n")
    out(__doc__)
    return 0

# open a file &amp; return the file object; gripe and return 0 if it
# couldn't be opened
def fopen(fname):
    try:
        return open(fname)
    except IOError as detail:
        return fail("couldn't open " + fname + ": " + str(detail))

# open two files &amp; spray the diff to stdout; return false iff a problem
def fcompare(f1name, f2name):
    f1 = fopen(f1name)
    f2 = fopen(f2name)
    if not f1 or not f2:
        return 0

    a = f1.readlines(); f1.close()
    b = f2.readlines(); f2.close()
    for line in difflib.ndiff(a, b):
        print(line, end=' ')

    return 1

# crack args (sys.argv[1:] is normal) &amp; compare;
# return false iff a problem

def main(args):
    import getopt
    try:
        opts, args = getopt.getopt(args, "qr:")
    except getopt.error as detail:
        return fail(str(detail))
    noisy = 1
    qseen = rseen = 0
    for opt, val in opts:
        if opt == "-q":
            qseen = 1
            noisy = 0
        elif opt == "-r":
            rseen = 1
            whichfile = val
    if qseen and rseen:
        return fail("can't specify both -q and -r")
    if rseen:
        if args:
            return fail("no args allowed with -r option")
        if whichfile in ("1", "2"):
            restore(whichfile)
            return 1
        return fail("-r value must be 1 or 2")
    if len(args) != 2:
        return fail("need 2 filename args")
    f1name, f2name = args
    if noisy:
        print('-:', f1name)
        print('+:', f2name)
    return fcompare(f1name, f2name)

# read ndiff output from stdin, and print file1 (which=='1') or
# file2 (which=='2') to stdout

def restore(which):
    restored = difflib.restore(sys.stdin.readlines(), which)
    sys.stdout.writelines(restored)

if __name__ == '__main__':
    main(sys.argv[1:])
</pre> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/difflib.html" class="_attribution-link">https://docs.python.org/3.12/library/difflib.html</a>
  </p>
</div>