/Doc/library/difflib.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 761 lines · 550 code · 211 blank · 0 comment · 0 complexity · 362f58373750a1d90bc5d57c2ede098d MD5 · raw file

  1. :mod:`difflib` --- Helpers for computing deltas
  2. ===============================================
  3. .. module:: difflib
  4. :synopsis: Helpers for computing differences between objects.
  5. .. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net>
  6. .. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net>
  7. .. Markup by Fred L. Drake, Jr. <fdrake@acm.org>
  8. .. testsetup::
  9. import sys
  10. from difflib import *
  11. .. versionadded:: 2.1
  12. This module provides classes and functions for comparing sequences. It
  13. can be used for example, for comparing files, and can produce difference
  14. information in various formats, including HTML and context and unified
  15. diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
  16. .. class:: SequenceMatcher
  17. This is a flexible class for comparing pairs of sequences of any type, so long
  18. as the sequence elements are :term:`hashable`. The basic algorithm predates, and is a
  19. little fancier than, an algorithm published in the late 1980's by Ratcliff and
  20. Obershelp under the hyperbolic name "gestalt pattern matching." The idea is to
  21. find the longest contiguous matching subsequence that contains no "junk"
  22. elements (the Ratcliff and Obershelp algorithm doesn't address junk). The same
  23. idea is then applied recursively to the pieces of the sequences to the left and
  24. to the right of the matching subsequence. This does not yield minimal edit
  25. sequences, but does tend to yield matches that "look right" to people.
  26. **Timing:** The basic Ratcliff-Obershelp algorithm is cubic time in the worst
  27. case and quadratic time in the expected case. :class:`SequenceMatcher` is
  28. quadratic time for the worst case and has expected-case behavior dependent in a
  29. complicated way on how many elements the sequences have in common; best case
  30. time is linear.
  31. .. class:: Differ
  32. This is a class for comparing sequences of lines of text, and producing
  33. human-readable differences or deltas. Differ uses :class:`SequenceMatcher`
  34. both to compare sequences of lines, and to compare sequences of characters
  35. within similar (near-matching) lines.
  36. Each line of a :class:`Differ` delta begins with a two-letter code:
  37. +----------+-------------------------------------------+
  38. | Code | Meaning |
  39. +==========+===========================================+
  40. | ``'- '`` | line unique to sequence 1 |
  41. +----------+-------------------------------------------+
  42. | ``'+ '`` | line unique to sequence 2 |
  43. +----------+-------------------------------------------+
  44. | ``' '`` | line common to both sequences |
  45. +----------+-------------------------------------------+
  46. | ``'? '`` | line not present in either input sequence |
  47. +----------+-------------------------------------------+
  48. Lines beginning with '``?``' attempt to guide the eye to intraline differences,
  49. and were not present in either input sequence. These lines can be confusing if
  50. the sequences contain tab characters.
  51. .. class:: HtmlDiff
  52. This class can be used to create an HTML table (or a complete HTML file
  53. containing the table) showing a side by side, line by line comparison of text
  54. with inter-line and intra-line change highlights. The table can be generated in
  55. either full or contextual difference mode.
  56. The constructor for this class is:
  57. .. function:: __init__([tabsize][, wrapcolumn][, linejunk][, charjunk])
  58. Initializes instance of :class:`HtmlDiff`.
  59. *tabsize* is an optional keyword argument to specify tab stop spacing and
  60. defaults to ``8``.
  61. *wrapcolumn* is an optional keyword to specify column number where lines are
  62. broken and wrapped, defaults to ``None`` where lines are not wrapped.
  63. *linejunk* and *charjunk* are optional keyword arguments passed into ``ndiff()``
  64. (used by :class:`HtmlDiff` to generate the side by side HTML differences). See
  65. ``ndiff()`` documentation for argument default values and descriptions.
  66. The following methods are public:
  67. .. function:: make_file(fromlines, tolines [, fromdesc][, todesc][, context][, numlines])
  68. Compares *fromlines* and *tolines* (lists of strings) and returns a string which
  69. is a complete HTML file containing a table showing line by line differences with
  70. inter-line and intra-line changes highlighted.
  71. *fromdesc* and *todesc* are optional keyword arguments to specify from/to file
  72. column header strings (both default to an empty string).
  73. *context* and *numlines* are both optional keyword arguments. Set *context* to
  74. ``True`` when contextual differences are to be shown, else the default is
  75. ``False`` to show the full files. *numlines* defaults to ``5``. When *context*
  76. is ``True`` *numlines* controls the number of context lines which surround the
  77. difference highlights. When *context* is ``False`` *numlines* controls the
  78. number of lines which are shown before a difference highlight when using the
  79. "next" hyperlinks (setting to zero would cause the "next" hyperlinks to place
  80. the next difference highlight at the top of the browser without any leading
  81. context).
  82. .. function:: make_table(fromlines, tolines [, fromdesc][, todesc][, context][, numlines])
  83. Compares *fromlines* and *tolines* (lists of strings) and returns a string which
  84. is a complete HTML table showing line by line differences with inter-line and
  85. intra-line changes highlighted.
  86. The arguments for this method are the same as those for the :meth:`make_file`
  87. method.
  88. :file:`Tools/scripts/diff.py` is a command-line front-end to this class and
  89. contains a good example of its use.
  90. .. versionadded:: 2.4
  91. .. function:: context_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])
  92. Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
  93. generating the delta lines) in context diff format.
  94. Context diffs are a compact way of showing just the lines that have changed plus
  95. a few lines of context. The changes are shown in a before/after style. The
  96. number of context lines is set by *n* which defaults to three.
  97. By default, the diff control lines (those with ``***`` or ``---``) are created
  98. with a trailing newline. This is helpful so that inputs created from
  99. :func:`file.readlines` result in diffs that are suitable for use with
  100. :func:`file.writelines` since both the inputs and outputs have trailing
  101. newlines.
  102. For inputs that do not have trailing newlines, set the *lineterm* argument to
  103. ``""`` so that the output will be uniformly newline free.
  104. The context diff format normally has a header for filenames and modification
  105. times. Any or all of these may be specified using strings for *fromfile*,
  106. *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
  107. expressed in the format returned by :func:`time.ctime`. If not specified, the
  108. strings default to blanks.
  109. >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
  110. >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
  111. >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
  112. ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE
  113. *** before.py
  114. --- after.py
  115. ***************
  116. *** 1,4 ****
  117. ! bacon
  118. ! eggs
  119. ! ham
  120. guido
  121. --- 1,4 ----
  122. ! python
  123. ! eggy
  124. ! hamster
  125. guido
  126. See :ref:`difflib-interface` for a more detailed example.
  127. .. versionadded:: 2.3
  128. .. function:: get_close_matches(word, possibilities[, n][, cutoff])
  129. Return a list of the best "good enough" matches. *word* is a sequence for which
  130. close matches are desired (typically a string), and *possibilities* is a list of
  131. sequences against which to match *word* (typically a list of strings).
  132. Optional argument *n* (default ``3``) is the maximum number of close matches to
  133. return; *n* must be greater than ``0``.
  134. Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1].
  135. Possibilities that don't score at least that similar to *word* are ignored.
  136. The best (no more than *n*) matches among the possibilities are returned in a
  137. list, sorted by similarity score, most similar first.
  138. >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
  139. ['apple', 'ape']
  140. >>> import keyword
  141. >>> get_close_matches('wheel', keyword.kwlist)
  142. ['while']
  143. >>> get_close_matches('apple', keyword.kwlist)
  144. []
  145. >>> get_close_matches('accept', keyword.kwlist)
  146. ['except']
  147. .. function:: ndiff(a, b[, linejunk][, charjunk])
  148. Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style
  149. delta (a :term:`generator` generating the delta lines).
  150. Optional keyword parameters *linejunk* and *charjunk* are for filter functions
  151. (or ``None``):
  152. *linejunk*: A function that accepts a single string argument, and returns true
  153. if the string is junk, or false if not. The default is (``None``), starting with
  154. Python 2.3. Before then, the default was the module-level function
  155. :func:`IS_LINE_JUNK`, which filters out lines without visible characters, except
  156. for at most one pound character (``'#'``). As of Python 2.3, the underlying
  157. :class:`SequenceMatcher` class does a dynamic analysis of which lines are so
  158. frequent as to constitute noise, and this usually works better than the pre-2.3
  159. default.
  160. *charjunk*: A function that accepts a character (a string of length 1), and
  161. returns if the character is junk, or false if not. The default is module-level
  162. function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a
  163. blank or tab; note: bad idea to include newline in this!).
  164. :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function.
  165. >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
  166. ... 'ore\ntree\nemu\n'.splitlines(1))
  167. >>> print ''.join(diff),
  168. - one
  169. ? ^
  170. + ore
  171. ? ^
  172. - two
  173. - three
  174. ? -
  175. + tree
  176. + emu
  177. .. function:: restore(sequence, which)
  178. Return one of the two sequences that generated a delta.
  179. Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract
  180. lines originating from file 1 or 2 (parameter *which*), stripping off line
  181. prefixes.
  182. Example:
  183. >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
  184. ... 'ore\ntree\nemu\n'.splitlines(1))
  185. >>> diff = list(diff) # materialize the generated delta into a list
  186. >>> print ''.join(restore(diff, 1)),
  187. one
  188. two
  189. three
  190. >>> print ''.join(restore(diff, 2)),
  191. ore
  192. tree
  193. emu
  194. .. function:: unified_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])
  195. Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
  196. generating the delta lines) in unified diff format.
  197. Unified diffs are a compact way of showing just the lines that have changed plus
  198. a few lines of context. The changes are shown in a inline style (instead of
  199. separate before/after blocks). The number of context lines is set by *n* which
  200. defaults to three.
  201. By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are
  202. created with a trailing newline. This is helpful so that inputs created from
  203. :func:`file.readlines` result in diffs that are suitable for use with
  204. :func:`file.writelines` since both the inputs and outputs have trailing
  205. newlines.
  206. For inputs that do not have trailing newlines, set the *lineterm* argument to
  207. ``""`` so that the output will be uniformly newline free.
  208. The context diff format normally has a header for filenames and modification
  209. times. Any or all of these may be specified using strings for *fromfile*,
  210. *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
  211. expressed in the format returned by :func:`time.ctime`. If not specified, the
  212. strings default to blanks.
  213. >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
  214. >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
  215. >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
  216. ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE
  217. --- before.py
  218. +++ after.py
  219. @@ -1,4 +1,4 @@
  220. -bacon
  221. -eggs
  222. -ham
  223. +python
  224. +eggy
  225. +hamster
  226. guido
  227. See :ref:`difflib-interface` for a more detailed example.
  228. .. versionadded:: 2.3
  229. .. function:: IS_LINE_JUNK(line)
  230. Return true for ignorable lines. The line *line* is ignorable if *line* is
  231. blank or contains a single ``'#'``, otherwise it is not ignorable. Used as a
  232. default for parameter *linejunk* in :func:`ndiff` before Python 2.3.
  233. .. function:: IS_CHARACTER_JUNK(ch)
  234. Return true for ignorable characters. The character *ch* is ignorable if *ch*
  235. is a space or tab, otherwise it is not ignorable. Used as a default for
  236. parameter *charjunk* in :func:`ndiff`.
  237. .. seealso::
  238. `Pattern Matching: The Gestalt Approach <http://www.ddj.com/184407970?pgno=5>`_
  239. Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
  240. was published in `Dr. Dobb's Journal <http://www.ddj.com/>`_ in July, 1988.
  241. .. _sequence-matcher:
  242. SequenceMatcher Objects
  243. -----------------------
  244. The :class:`SequenceMatcher` class has this constructor:
  245. .. class:: SequenceMatcher([isjunk[, a[, b]]])
  246. Optional argument *isjunk* must be ``None`` (the default) or a one-argument
  247. function that takes a sequence element and returns true if and only if the
  248. element is "junk" and should be ignored. Passing ``None`` for *isjunk* is
  249. equivalent to passing ``lambda x: 0``; in other words, no elements are ignored.
  250. For example, pass::
  251. lambda x: x in " \t"
  252. if you're comparing lines as sequences of characters, and don't want to synch up
  253. on blanks or hard tabs.
  254. The optional arguments *a* and *b* are sequences to be compared; both default to
  255. empty strings. The elements of both sequences must be :term:`hashable`.
  256. :class:`SequenceMatcher` objects have the following methods:
  257. .. method:: set_seqs(a, b)
  258. Set the two sequences to be compared.
  259. :class:`SequenceMatcher` computes and caches detailed information about the
  260. second sequence, so if you want to compare one sequence against many
  261. sequences, use :meth:`set_seq2` to set the commonly used sequence once and
  262. call :meth:`set_seq1` repeatedly, once for each of the other sequences.
  263. .. method:: set_seq1(a)
  264. Set the first sequence to be compared. The second sequence to be compared
  265. is not changed.
  266. .. method:: set_seq2(b)
  267. Set the second sequence to be compared. The first sequence to be compared
  268. is not changed.
  269. .. method:: find_longest_match(alo, ahi, blo, bhi)
  270. Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
  271. If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
  272. ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
  273. <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
  274. k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
  275. <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
  276. all maximal matching blocks, return one that starts earliest in *a*, and
  277. of all those maximal matching blocks that start earliest in *a*, return
  278. the one that starts earliest in *b*.
  279. >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
  280. >>> s.find_longest_match(0, 5, 0, 9)
  281. Match(a=0, b=4, size=5)
  282. If *isjunk* was provided, first the longest matching block is determined
  283. as above, but with the additional restriction that no junk element appears
  284. in the block. Then that block is extended as far as possible by matching
  285. (only) junk elements on both sides. So the resulting block never matches
  286. on junk except as identical junk happens to be adjacent to an interesting
  287. match.
  288. Here's the same example as before, but considering blanks to be junk. That
  289. prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the
  290. second sequence directly. Instead only the ``'abcd'`` can match, and
  291. matches the leftmost ``'abcd'`` in the second sequence:
  292. >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
  293. >>> s.find_longest_match(0, 5, 0, 9)
  294. Match(a=1, b=0, size=4)
  295. If no blocks match, this returns ``(alo, blo, 0)``.
  296. .. versionchanged:: 2.6
  297. This method returns a :term:`named tuple` ``Match(a, b, size)``.
  298. .. method:: get_matching_blocks()
  299. Return list of triples describing matching subsequences. Each triple is of
  300. the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The
  301. triples are monotonically increasing in *i* and *j*.
  302. The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It
  303. is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')``
  304. are adjacent triples in the list, and the second is not the last triple in
  305. the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent
  306. triples always describe non-adjacent equal blocks.
  307. .. XXX Explain why a dummy is used!
  308. .. versionchanged:: 2.5
  309. The guarantee that adjacent triples always describe non-adjacent blocks
  310. was implemented.
  311. .. doctest::
  312. >>> s = SequenceMatcher(None, "abxcd", "abcd")
  313. >>> s.get_matching_blocks()
  314. [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
  315. .. method:: get_opcodes()
  316. Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
  317. of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 ==
  318. 0``, and remaining tuples have *i1* equal to the *i2* from the preceding
  319. tuple, and, likewise, *j1* equal to the previous *j2*.
  320. The *tag* values are strings, with these meanings:
  321. +---------------+---------------------------------------------+
  322. | Value | Meaning |
  323. +===============+=============================================+
  324. | ``'replace'`` | ``a[i1:i2]`` should be replaced by |
  325. | | ``b[j1:j2]``. |
  326. +---------------+---------------------------------------------+
  327. | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that |
  328. | | ``j1 == j2`` in this case. |
  329. +---------------+---------------------------------------------+
  330. | ``'insert'`` | ``b[j1:j2]`` should be inserted at |
  331. | | ``a[i1:i1]``. Note that ``i1 == i2`` in |
  332. | | this case. |
  333. +---------------+---------------------------------------------+
  334. | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
  335. | | are equal). |
  336. +---------------+---------------------------------------------+
  337. For example:
  338. >>> a = "qabxcd"
  339. >>> b = "abycdf"
  340. >>> s = SequenceMatcher(None, a, b)
  341. >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
  342. ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
  343. ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
  344. delete a[0:1] (q) b[0:0] ()
  345. equal a[1:3] (ab) b[0:2] (ab)
  346. replace a[3:4] (x) b[2:3] (y)
  347. equal a[4:6] (cd) b[3:5] (cd)
  348. insert a[6:6] () b[5:6] (f)
  349. .. method:: get_grouped_opcodes([n])
  350. Return a :term:`generator` of groups with up to *n* lines of context.
  351. Starting with the groups returned by :meth:`get_opcodes`, this method
  352. splits out smaller change clusters and eliminates intervening ranges which
  353. have no changes.
  354. The groups are returned in the same format as :meth:`get_opcodes`.
  355. .. versionadded:: 2.3
  356. .. method:: ratio()
  357. Return a measure of the sequences' similarity as a float in the range [0,
  358. 1].
  359. Where T is the total number of elements in both sequences, and M is the
  360. number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
  361. sequences are identical, and ``0.0`` if they have nothing in common.
  362. This is expensive to compute if :meth:`get_matching_blocks` or
  363. :meth:`get_opcodes` hasn't already been called, in which case you may want
  364. to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an
  365. upper bound.
  366. .. method:: quick_ratio()
  367. Return an upper bound on :meth:`ratio` relatively quickly.
  368. This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
  369. is faster to compute.
  370. .. method:: real_quick_ratio()
  371. Return an upper bound on :meth:`ratio` very quickly.
  372. This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
  373. is faster to compute than either :meth:`ratio` or :meth:`quick_ratio`.
  374. The three methods that return the ratio of matching to total characters can give
  375. different results due to differing levels of approximation, although
  376. :meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as
  377. :meth:`ratio`:
  378. >>> s = SequenceMatcher(None, "abcd", "bcde")
  379. >>> s.ratio()
  380. 0.75
  381. >>> s.quick_ratio()
  382. 0.75
  383. >>> s.real_quick_ratio()
  384. 1.0
  385. .. _sequencematcher-examples:
  386. SequenceMatcher Examples
  387. ------------------------
  388. This example compares two strings, considering blanks to be "junk:"
  389. >>> s = SequenceMatcher(lambda x: x == " ",
  390. ... "private Thread currentThread;",
  391. ... "private volatile Thread currentThread;")
  392. :meth:`ratio` returns a float in [0, 1], measuring the similarity of the
  393. sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the
  394. sequences are close matches:
  395. >>> print round(s.ratio(), 3)
  396. 0.866
  397. If you're only interested in where the sequences match,
  398. :meth:`get_matching_blocks` is handy:
  399. >>> for block in s.get_matching_blocks():
  400. ... print "a[%d] and b[%d] match for %d elements" % block
  401. a[0] and b[0] match for 8 elements
  402. a[8] and b[17] match for 21 elements
  403. a[29] and b[38] match for 0 elements
  404. Note that the last tuple returned by :meth:`get_matching_blocks` is always a
  405. dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last
  406. tuple element (number of elements matched) is ``0``.
  407. If you want to know how to change the first sequence into the second, use
  408. :meth:`get_opcodes`:
  409. >>> for opcode in s.get_opcodes():
  410. ... print "%6s a[%d:%d] b[%d:%d]" % opcode
  411. equal a[0:8] b[0:8]
  412. insert a[8:8] b[8:17]
  413. equal a[8:29] b[17:38]
  414. See also the function :func:`get_close_matches` in this module, which shows how
  415. simple code building on :class:`SequenceMatcher` can be used to do useful work.
  416. .. _differ-objects:
  417. Differ Objects
  418. --------------
  419. Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
  420. diffs. To the contrary, minimal diffs are often counter-intuitive, because they
  421. synch up anywhere possible, sometimes accidental matches 100 pages apart.
  422. Restricting synch points to contiguous matches preserves some notion of
  423. locality, at the occasional cost of producing a longer diff.
  424. The :class:`Differ` class has this constructor:
  425. .. class:: Differ([linejunk[, charjunk]])
  426. Optional keyword parameters *linejunk* and *charjunk* are for filter functions
  427. (or ``None``):
  428. *linejunk*: A function that accepts a single string argument, and returns true
  429. if the string is junk. The default is ``None``, meaning that no line is
  430. considered junk.
  431. *charjunk*: A function that accepts a single character argument (a string of
  432. length 1), and returns true if the character is junk. The default is ``None``,
  433. meaning that no character is considered junk.
  434. :class:`Differ` objects are used (deltas generated) via a single method:
  435. .. method:: Differ.compare(a, b)
  436. Compare two sequences of lines, and generate the delta (a sequence of lines).
  437. Each sequence must contain individual single-line strings ending with newlines.
  438. Such sequences can be obtained from the :meth:`readlines` method of file-like
  439. objects. The delta generated also consists of newline-terminated strings, ready
  440. to be printed as-is via the :meth:`writelines` method of a file-like object.
  441. .. _differ-examples:
  442. Differ Example
  443. --------------
  444. This example compares two texts. First we set up the texts, sequences of
  445. individual single-line strings ending with newlines (such sequences can also be
  446. obtained from the :meth:`readlines` method of file-like objects):
  447. >>> text1 = ''' 1. Beautiful is better than ugly.
  448. ... 2. Explicit is better than implicit.
  449. ... 3. Simple is better than complex.
  450. ... 4. Complex is better than complicated.
  451. ... '''.splitlines(1)
  452. >>> len(text1)
  453. 4
  454. >>> text1[0][-1]
  455. '\n'
  456. >>> text2 = ''' 1. Beautiful is better than ugly.
  457. ... 3. Simple is better than complex.
  458. ... 4. Complicated is better than complex.
  459. ... 5. Flat is better than nested.
  460. ... '''.splitlines(1)
  461. Next we instantiate a Differ object:
  462. >>> d = Differ()
  463. Note that when instantiating a :class:`Differ` object we may pass functions to
  464. filter out line and character "junk." See the :meth:`Differ` constructor for
  465. details.
  466. Finally, we compare the two:
  467. >>> result = list(d.compare(text1, text2))
  468. ``result`` is a list of strings, so let's pretty-print it:
  469. >>> from pprint import pprint
  470. >>> pprint(result)
  471. [' 1. Beautiful is better than ugly.\n',
  472. '- 2. Explicit is better than implicit.\n',
  473. '- 3. Simple is better than complex.\n',
  474. '+ 3. Simple is better than complex.\n',
  475. '? ++\n',
  476. '- 4. Complex is better than complicated.\n',
  477. '? ^ ---- ^\n',
  478. '+ 4. Complicated is better than complex.\n',
  479. '? ++++ ^ ^\n',
  480. '+ 5. Flat is better than nested.\n']
  481. As a single multi-line string it looks like this:
  482. >>> import sys
  483. >>> sys.stdout.writelines(result)
  484. 1. Beautiful is better than ugly.
  485. - 2. Explicit is better than implicit.
  486. - 3. Simple is better than complex.
  487. + 3. Simple is better than complex.
  488. ? ++
  489. - 4. Complex is better than complicated.
  490. ? ^ ---- ^
  491. + 4. Complicated is better than complex.
  492. ? ++++ ^ ^
  493. + 5. Flat is better than nested.
  494. .. _difflib-interface:
  495. A command-line interface to difflib
  496. -----------------------------------
  497. This example shows how to use difflib to create a ``diff``-like utility.
  498. It is also contained in the Python source distribution, as
  499. :file:`Tools/scripts/diff.py`.
  500. .. testcode::
  501. """ Command line interface to difflib.py providing diffs in four formats:
  502. * ndiff: lists every line and highlights interline changes.
  503. * context: highlights clusters of changes in a before/after format.
  504. * unified: highlights clusters of changes in an inline format.
  505. * html: generates side by side comparison with change highlights.
  506. """
  507. import sys, os, time, difflib, optparse
  508. def main():
  509. # Configure the option parser
  510. usage = "usage: %prog [options] fromfile tofile"
  511. parser = optparse.OptionParser(usage)
  512. parser.add_option("-c", action="store_true", default=False,
  513. help='Produce a context format diff (default)')
  514. parser.add_option("-u", action="store_true", default=False,
  515. help='Produce a unified format diff')
  516. hlp = 'Produce HTML side by side diff (can use -c and -l in conjunction)'
  517. parser.add_option("-m", action="store_true", default=False, help=hlp)
  518. parser.add_option("-n", action="store_true", default=False,
  519. help='Produce a ndiff format diff')
  520. parser.add_option("-l", "--lines", type="int", default=3,
  521. help='Set number of context lines (default 3)')
  522. (options, args) = parser.parse_args()
  523. if len(args) == 0:
  524. parser.print_help()
  525. sys.exit(1)
  526. if len(args) != 2:
  527. parser.error("need to specify both a fromfile and tofile")
  528. n = options.lines
  529. fromfile, tofile = args # as specified in the usage string
  530. # we're passing these as arguments to the diff function
  531. fromdate = time.ctime(os.stat(fromfile).st_mtime)
  532. todate = time.ctime(os.stat(tofile).st_mtime)
  533. fromlines = open(fromfile, 'U').readlines()
  534. tolines = open(tofile, 'U').readlines()
  535. if options.u:
  536. diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile,
  537. fromdate, todate, n=n)
  538. elif options.n:
  539. diff = difflib.ndiff(fromlines, tolines)
  540. elif options.m:
  541. diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile,
  542. tofile, context=options.c,
  543. numlines=n)
  544. else:
  545. diff = difflib.context_diff(fromlines, tolines, fromfile, tofile,
  546. fromdate, todate, n=n)
  547. # we're using writelines because diff is a generator
  548. sys.stdout.writelines(diff)
  549. if __name__ == '__main__':
  550. main()