“Python/docs/3.9/library/2to3”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/2to3
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:2to3 - 自动 Python 2 到 3 代码转换 — Python 文档}}
 
<div id="to3-automated-python-2-to-3-code-translation" class="section">
 
<div id="to3-automated-python-2-to-3-code-translation" class="section">
  
 
<span id="to3-reference"></span>
 
<span id="to3-reference"></span>
= 2to3 - Automated Python 2 to 3 code translation =
+
= 2to3 - 自动 Python 2 3 代码翻译 =
  
2to3 is a Python program that reads Python 2.x source code and applies a series
+
2to3 是一个 Python 程序,它读取 Python 2.x 源代码并应用一系列 ''修复程序'' 将其转换为有效的 Python 3.x 代码。 标准库包含一组丰富的修复程序,可以处理几乎所有代码。 然而,2to3 支持库 [[#module-lib2to3|lib2to3]] 是一个灵活的通用库,因此可以为 2to3 编写自己的修复程序。
of ''fixers'' to transform it into valid Python 3.x code. The standard library
 
contains a rich set of fixers that will handle almost all code. 2to3 supporting
 
library [[#module-lib2to3|<code>lib2to3</code>]] is, however, a flexible and generic library, so it is
 
possible to write your own fixers for 2to3.
 
  
 
<div id="using-2to3" class="section">
 
<div id="using-2to3" class="section">
  
 
<span id="to3-using"></span>
 
<span id="to3-using"></span>
== Using 2to3 ==
+
== 使用 2to3 ==
  
2to3 will usually be installed with the Python interpreter as a script. It is
+
2to3 通常会作为脚本与 Python 解释器一起安装。 它也位于 Python 根目录的 <code>Tools/scripts</code> 目录中。
also located in the <code>Tools/scripts</code> directory of the Python root.
 
  
2to3's basic arguments are a list of files or directories to transform. The
+
2to3 的基本参数是要转换的文件或目录列表。 递归遍历目录以获取 Python 源代码。
directories are recursively traversed for Python sources.
 
  
Here is a sample Python 2.x source file, <code>example.py</code>:
+
这是一个示例 Python 2.x 源文件,<code>example.py</code>
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第27行: 第22行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def greet(name):
+
<syntaxhighlight lang="python3">def greet(name):
     print &quot;Hello, {0}!&quot;.format(name)
+
     print "Hello, {0}!".format(name)
print &quot;What's your name?&quot;
+
print "What's your name?"
 
name = raw_input()
 
name = raw_input()
greet(name)</pre>
+
greet(name)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
It can be converted to Python 3.x code via 2to3 on the command line:
+
可以通过命令行中的 2to3 将其转换为 Python 3.x 代码:
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第42行: 第37行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ 2to3 example.py</pre>
+
<pre class="session">$ 2to3 example.py</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
A diff against the original source file is printed. 2to3 can also write the
+
打印与原始源文件的差异。 2to3 还可以将所需的修改写回源文件。 (除非还给出了 <code>-n</code>,否则会备份原始文件。)使用 <code>-w</code> 标志启用回写更改:
needed modifications right back to the source file. (A backup of the original
 
file is made unless <code>-n</code> is also given.) Writing the changes back is
 
enabled with the <code>-w</code> flag:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第56行: 第48行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ 2to3 -w example.py</pre>
+
<pre class="session">$ 2to3 -w example.py</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
After transformation, <code>example.py</code> looks like this:
+
改造后的 <code>example.py</code> 长这样:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第67行: 第59行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def greet(name):
+
<syntaxhighlight lang="python3">def greet(name):
     print(&quot;Hello, {0}!&quot;.format(name))
+
     print("Hello, {0}!".format(name))
print(&quot;What's your name?&quot;)
+
print("What's your name?")
 
name = input()
 
name = input()
greet(name)</pre>
+
greet(name)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Comments and exact indentation are preserved throughout the translation process.
+
在整个翻译过程中保留注释和精确缩进。
  
By default, 2to3 runs a set of [[#to3-fixers|<span class="std std-ref">predefined fixers</span>]]. The
+
默认情况下,2to3 运行一组 [[#to3-fixers|预定义的修复程序]] <code>-l</code> 标志列出了所有可用的修复程序。 可以使用 <code>-f</code> 给出一组明确的要运行的修复程序。 同样,<code>-x</code> 明确禁用了一个固定器。 以下示例仅运行 <code>imports</code> <code>has_key</code> 修复程序:
<code>-l</code> flag lists all available fixers. An explicit set of fixers to run
 
can be given with <code>-f</code>. Likewise the <code>-x</code> explicitly disables a
 
fixer. The following example runs only the <code>imports</code> and <code>has_key</code> fixers:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第87行: 第76行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ 2to3 -f imports -f has_key example.py</pre>
+
<pre class="session">$ 2to3 -f imports -f has_key example.py</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
This command runs every fixer except the <code>apply</code> fixer:
+
此命令运行除 <code>apply</code> 固定器之外的所有固定器:
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第98行: 第87行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ 2to3 -x apply example.py</pre>
+
<pre class="session">$ 2to3 -x apply example.py</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Some fixers are ''explicit'', meaning they aren't run by default and must be
+
一些修复程序是 ''explicit'',这意味着它们默认不运行,必须在命令行中列出才能运行。 在这里,除了默认的修复程序之外,还运行 <code>idioms</code> 修复程序:
listed on the command line to be run. Here, in addition to the default fixers,
 
the <code>idioms</code> fixer is run:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第111行: 第98行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ 2to3 -f all -f idioms example.py</pre>
+
<pre class="session">$ 2to3 -f all -f idioms example.py</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Notice how passing <code>all</code> enables all default fixers.
+
请注意传递 <code>all</code> 如何启用所有默认修复程序。
  
Sometimes 2to3 will find a place in your source code that needs to be changed,
+
有时 2to3 会在您的源代码中找到需要更改的地方,但 2to3 无法自动修复。 在这种情况下, 2to3 将在文件的差异下方打印警告。 您应该解决警告以获得兼容的 3.x 代码。
but 2to3 cannot fix automatically. In this case, 2to3 will print a warning
 
beneath the diff for a file. You should address the warning in order to have
 
compliant 3.x code.
 
  
2to3 can also refactor doctests. To enable this mode, use the <code>-d</code>
+
2to3 还可以重构 doctest。 要启用此模式,请使用 <code>-d</code> 标志。 请注意,''only'' doctests 将被重构。 这也不要求模块是有效的 Python。 例如,也可以使用此选项重构 reST 文档中类似 doctest 的示例。
flag. Note that ''only'' doctests will be refactored. This also doesn't require
 
the module to be valid Python. For example, doctest like examples in a reST
 
document could also be refactored with this option.
 
  
The <code>-v</code> option enables output of more information on the translation
+
<code>-v</code> 选项可以输出有关翻译过程的更多信息。
process.
 
  
Since some print statements can be parsed as function calls or statements, 2to3
+
由于某些打印语句可以解析为函数调用或语句,因此 2to3 不能总是读取包含打印函数的文件。 当 2to3 检测到 <code>from __future__ import print_function</code> 编译器指令的存在时,它会修改其内部语法以将 [[../functions#print|print()]] 解释为函数。 也可以使用 <code>-p</code> 标志手动启用此更改。 使用 <code>-p</code> 在已转换其打印语句的代码上运行修复程序。 <code>-e</code> 也可用于使 [[../functions#exec|exec()]] 成为一个函数。
cannot always read files containing the print function. When 2to3 detects the
 
presence of the <code>from __future__ import print_function</code> compiler directive, it
 
modifies its internal grammar to interpret [[../functions#print|<code>print()</code>]] as a function. This
 
change can also be enabled manually with the <code>-p</code> flag. Use
 
<code>-p</code> to run fixers on code that already has had its print statements
 
converted. Also <code>-e</code> can be used to make [[../functions#exec|<code>exec()</code>]] a function.
 
  
The <code>-o</code> or <code>--output-dir</code> option allows specification of an
+
<code>-o</code> <code>--output-dir</code> 选项允许指定用于写入已处理输出文件的备用目录。 <code>-n</code> 标志在使用它时需要,因为当不覆盖输入文件时,备份文件没有意义。
alternate directory for processed output files to be written to. The
 
<code>-n</code> flag is required when using this as backup files do not make sense
 
when not overwriting the input files.
 
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.2.3 新版功能: </span>The <code>-o</code> option was added.
+
<span class="versionmodified added"> 3.2.3 新功能: </span> 增加了 <code>-o</code> 选项。
  
  
 
</div>
 
</div>
The <code>-W</code> or <code>--write-unchanged-files</code> flag tells 2to3 to always
+
<code>-W</code> <code>--write-unchanged-files</code> 标志告诉 2to3 始终写入输出文件,即使文件不需要更改。 这对 <code>-o</code> 最有用,以便将整个 Python 源代码树复制并从一个目录转换到另一个目录。 这个选项意味着 <code>-w</code> 标志,否则它没有意义。
write output files even if no changes were required to the file. This is most
 
useful with <code>-o</code> so that an entire Python source tree is copied with
 
translation from one directory to another.
 
This option implies the <code>-w</code> flag as it would not make sense otherwise.
 
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.2.3 新版功能: </span>The <code>-W</code> flag was added.
+
<span class="versionmodified added"> 3.2.3 新功能: </span> 增加了 <code>-W</code> 标志。
  
  
 
</div>
 
</div>
The <code>--add-suffix</code> option specifies a string to append to all output
+
<code>--add-suffix</code> 选项指定要附加到所有输出文件名的字符串。 指定此选项时需要 <code>-n</code> 标志,因为在写入不同的文件名时不需要备份。 例子:
filenames. The <code>-n</code> flag is required when specifying this as backups
 
are not necessary when writing to different filenames. Example:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第170行: 第135行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ 2to3 -n -W --add-suffix=3 example.py</pre>
+
<pre class="session">$ 2to3 -n -W --add-suffix=3 example.py</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Will cause a converted file named <code>example.py3</code> to be written.
+
将导致写入名为 <code>example.py3</code> 的转换文件。
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.2.3 新版功能: </span>The <code>--add-suffix</code> option was added.
+
<span class="versionmodified added"> 3.2.3 新功能: </span> 增加了 <code>--add-suffix</code> 选项。
  
  
 
</div>
 
</div>
To translate an entire project from one directory tree to another use:
+
要将整个项目从一个目录树转换为另一种使用:
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第189行: 第154行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode</pre>
+
<pre class="session">$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode</pre>
  
 
</div>
 
</div>
第199行: 第164行:
  
 
<span id="to3-fixers"></span>
 
<span id="to3-fixers"></span>
== Fixers ==
+
== 修理工 ==
  
Each step of transforming code is encapsulated in a fixer. The command <code>2to3 -l</code> lists them. As [[#to3-using|<span class="std std-ref">documented above</span>]], each can be turned on
+
转换代码的每一步都封装在一个固定器中。 命令 <code>2to3 -l</code> 列出了它们。 正如上面[[#to3-using|所述的]],每个都可以单独打开和关闭。 此处更详细地描述了它们。
and off individually. They are described here in more detail.
 
  
; <span id="2to3fixer-apply"></span><code>apply</code>
 
: Removes usage of <code>apply()</code>. For example <code>apply(function, *args, **kwargs)</code> is converted to <code>function(*args, **kwargs)</code>.
 
  
<dl>
+
</div>
<dt><span id="2to3fixer-asserts"></span><code>asserts</code></dt>
+
<div id="module-lib2to3" class="section">
<dd><p>Replaces deprecated [[../unittest#module-unittest|<code>unittest</code>]] method names with the correct ones.</p>
 
{|
 
!width="43%"| <p>From</p>
 
!width="56%"| <p>To</p>
 
|-
 
| <p><code>failUnlessEqual(a, b)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertEqual(a, b)</code>]]</p>
 
|-
 
| <p><code>assertEquals(a, b)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertEqual(a, b)</code>]]</p>
 
|-
 
| <p><code>failIfEqual(a, b)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertNotEqual(a, b)</code>]]</p>
 
|-
 
| <p><code>assertNotEquals(a, b)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertNotEqual(a, b)</code>]]</p>
 
|-
 
| <p><code>failUnless(a)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertTrue(a)</code>]]</p>
 
|-
 
| <p><code>assert_(a)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertTrue(a)</code>]]</p>
 
|-
 
| <p><code>failIf(a)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertFalse(a)</code>]]</p>
 
|-
 
| <p><code>failUnlessRaises(exc, cal)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertRaises(exc, cal)</code>]]</p>
 
|-
 
| <p><code>failUnlessAlmostEqual(a, b)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertAlmostEqual(a, b)</code>]]</p>
 
|-
 
| <p><code>assertAlmostEquals(a, b)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertAlmostEqual(a, b)</code>]]</p>
 
|-
 
| <p><code>failIfAlmostEqual(a, b)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertNotAlmostEqual(a, b)</code>]]</p>
 
|-
 
| <p><code>assertNotAlmostEquals(a, b)</code></p>
 
| <p>[[../unittest#unittest.TestCase|<code>assertNotAlmostEqual(a, b)</code>]]</p>
 
|}
 
</dd></dl>
 
  
; <span id="2to3fixer-basestring"></span><code>basestring</code>
+
<span id="lib2to3-2to3-s-library"></span>
: Converts <code>basestring</code> to [[../stdtypes#str|<code>str</code>]].
+
== lib2to3 - 2to3 的库 ==
  
; <span id="2to3fixer-buffer"></span><code>buffer</code>
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/lib2to3/`</span>]]
: Converts <code>buffer</code> to [[../stdtypes#memoryview|<code>memoryview</code>]]. This fixer is optional because the [[../stdtypes#memoryview|<code>memoryview</code>]] API is similar but not exactly the same as that of <code>buffer</code>.
 
  
; <span id="2to3fixer-dict"></span><code>dict</code>
 
: Fixes dictionary iteration methods. <code>dict.iteritems()</code> is converted to [[../stdtypes#dict|<code>dict.items()</code>]], <code>dict.iterkeys()</code> to [[../stdtypes#dict|<code>dict.keys()</code>]], and <code>dict.itervalues()</code> to [[../stdtypes#dict|<code>dict.values()</code>]]. Similarly, <code>dict.viewitems()</code>, <code>dict.viewkeys()</code> and <code>dict.viewvalues()</code> are converted respectively to [[../stdtypes#dict|<code>dict.items()</code>]], [[../stdtypes#dict|<code>dict.keys()</code>]] and [[../stdtypes#dict|<code>dict.values()</code>]]. It also wraps existing usages of [[../stdtypes#dict|<code>dict.items()</code>]], [[../stdtypes#dict|<code>dict.keys()</code>]], and [[../stdtypes#dict|<code>dict.values()</code>]] in a call to [[../stdtypes#list|<code>list</code>]].
 
  
; <span id="2to3fixer-except"></span><code>except</code>
+
-----
: Converts <code>except X, T</code> to <code>except X as T</code>.
 
  
; <span id="2to3fixer-exec"></span><code>exec</code>
+
<div class="deprecated">
: Converts the <code>exec</code> statement to the [[../functions#exec|<code>exec()</code>]] function.
 
 
 
; <span id="2to3fixer-execfile"></span><code>execfile</code>
 
: Removes usage of <code>execfile()</code>. The argument to <code>execfile()</code> is wrapped in calls to [[../functions#open|<code>open()</code>]], [[../functions#compile|<code>compile()</code>]], and [[../functions#exec|<code>exec()</code>]].
 
 
 
; <span id="2to3fixer-exitfunc"></span><code>exitfunc</code>
 
: Changes assignment of <code>sys.exitfunc</code> to use of the [[../atexit#module-atexit|<code>atexit</code>]] module.
 
 
 
; <span id="2to3fixer-filter"></span><code>filter</code>
 
: Wraps [[../functions#filter|<code>filter()</code>]] usage in a [[../stdtypes#list|<code>list</code>]] call.
 
 
 
; <span id="2to3fixer-funcattrs"></span><code>funcattrs</code>
 
: Fixes function attributes that have been renamed. For example, <code>my_function.func_closure</code> is converted to <code>my_function.__closure__</code>.
 
 
 
; <span id="2to3fixer-future"></span><code>future</code>
 
: Removes <code>from __future__ import new_feature</code> statements.
 
 
 
; <span id="2to3fixer-getcwdu"></span><code>getcwdu</code>
 
: Renames <code>os.getcwdu()</code> to [[../os#os|<code>os.getcwd()</code>]].
 
  
; <span id="2to3fixer-has_key"></span><code>has_key</code>
+
<span class="versionmodified deprecated"> 自 3.10 版起已弃用:</span>Python 3.9 将切换到 PEG 解析器(请参阅 <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-0617 PEP 617]),并且 Python 3.10 可能包含无法解析的新语言语法lib2to3 的 LL(1) 解析器。 <code>lib2to3</code> 模块可能会在未来的 Python 版本中从标准库中删除。 考虑第三方替代方案,例如 [https://libcst.readthedocs.io/ LibCST] 或 [https://parso.readthedocs.io/ parso]。
: Changes <code>dict.has_key(key)</code> to <code>key in dict</code>.
 
  
<dl>
 
<dt><span id="2to3fixer-idioms"></span><code>idioms</code></dt>
 
<dd><p>This optional fixer performs several transformations that make Python code
 
more idiomatic. Type comparisons like <code>type(x) is SomeClass</code> and
 
<code>type(x) == SomeClass</code> are converted to <code>isinstance(x, SomeClass)</code>.
 
<code>while 1</code> becomes <code>while True</code>. This fixer also tries to make use of
 
[[../functions#sorted|<code>sorted()</code>]] in appropriate places. For example, this block</p>
 
<div class="highlight-python3 notranslate">
 
 
<div class="highlight">
 
 
<pre>L = list(some_iterable)
 
L.sort()</pre>
 
  
 
</div>
 
</div>
 +
<div class="admonition note">
  
</div>
+
笔记
<p>is changed to</p>
 
<div class="highlight-python3 notranslate">
 
  
<div class="highlight">
+
[[#module-lib2to3|lib2to3]] API 应该被认为是不稳定的,未来可能会发生巨大变化。
  
<pre>L = sorted(some_iterable)</pre>
 
  
 
</div>
 
</div>
 
</div></dd></dl>
 
 
; <span id="2to3fixer-import"></span><code>import</code>
 
: Detects sibling imports and converts them to relative imports.
 
 
; <span id="2to3fixer-imports"></span><code>imports</code>
 
: Handles module renames in the standard library.
 
 
; <span id="2to3fixer-imports2"></span><code>imports2</code>
 
: Handles other modules renames in the standard library. It is separate from the [[#to3fixer-imports|<code>imports</code>]] fixer only because of technical limitations.
 
 
; <span id="2to3fixer-input"></span><code>input</code>
 
: Converts <code>input(prompt)</code> to <code>eval(input(prompt))</code>.
 
 
; <span id="2to3fixer-intern"></span><code>intern</code>
 
: Converts <code>intern()</code> to [[../sys#sys|<code>sys.intern()</code>]].
 
 
; <span id="2to3fixer-isinstance"></span><code>isinstance</code>
 
: Fixes duplicate types in the second argument of [[../functions#isinstance|<code>isinstance()</code>]]. For example, <code>isinstance(x, (int, int))</code> is converted to <code>isinstance(x, int)</code> and <code>isinstance(x, (int, float, int))</code> is converted to <code>isinstance(x, (int, float))</code>.
 
 
; <span id="2to3fixer-itertools_imports"></span><code>itertools_imports</code>
 
: Removes imports of <code>itertools.ifilter()</code>, <code>itertools.izip()</code>, and <code>itertools.imap()</code>. Imports of <code>itertools.ifilterfalse()</code> are also changed to [[../itertools#itertools|<code>itertools.filterfalse()</code>]].
 
 
; <span id="2to3fixer-itertools"></span><code>itertools</code>
 
: Changes usage of <code>itertools.ifilter()</code>, <code>itertools.izip()</code>, and <code>itertools.imap()</code> to their built-in equivalents. <code>itertools.ifilterfalse()</code> is changed to [[../itertools#itertools|<code>itertools.filterfalse()</code>]].
 
 
; <span id="2to3fixer-long"></span><code>long</code>
 
: Renames <code>long</code> to [[../functions#int|<code>int</code>]].
 
 
; <span id="2to3fixer-map"></span><code>map</code>
 
: Wraps [[../functions#map|<code>map()</code>]] in a [[../stdtypes#list|<code>list</code>]] call. It also changes <code>map(None, x)</code> to <code>list(x)</code>. Using <code>from future_builtins import map</code> disables this fixer.
 
 
; <span id="2to3fixer-metaclass"></span><code>metaclass</code>
 
: Converts the old metaclass syntax (<code>__metaclass__ = Meta</code> in the class body) to the new (<code>class X(metaclass=Meta)</code>).
 
 
; <span id="2to3fixer-methodattrs"></span><code>methodattrs</code>
 
: Fixes old method attribute names. For example, <code>meth.im_func</code> is converted to <code>meth.__func__</code>.
 
 
; <span id="2to3fixer-ne"></span><code>ne</code>
 
: Converts the old not-equal syntax, <code>&lt;&gt;</code>, to <code>!=</code>.
 
 
; <span id="2to3fixer-next"></span><code>next</code>
 
: Converts the use of iterator's <code>next()</code> methods to the [[../functions#next|<code>next()</code>]] function. It also renames [[../functions#next|<code>next()</code>]] methods to [[../stdtypes#iterator|<code>__next__()</code>]].
 
 
; <span id="2to3fixer-nonzero"></span><code>nonzero</code>
 
: Renames <code>__nonzero__()</code> to [[../../reference/datamodel#object|<code>__bool__()</code>]].
 
 
; <span id="2to3fixer-numliterals"></span><code>numliterals</code>
 
: Converts octal literals into the new syntax.
 
 
<dl>
 
<dt><span id="2to3fixer-operator"></span><code>operator</code></dt>
 
<dd><p>Converts calls to various functions in the [[../operator#module-operator|<code>operator</code>]] module to other,
 
but equivalent, function calls. When needed, the appropriate <code>import</code>
 
statements are added, e.g. <code>import collections.abc</code>. The following mapping
 
are made:</p>
 
{|
 
!width="43%"| <p>From</p>
 
!width="56%"| <p>To</p>
 
|-
 
| <p><code>operator.isCallable(obj)</code></p>
 
| <p><code>callable(obj)</code></p>
 
|-
 
| <p><code>operator.sequenceIncludes(obj)</code></p>
 
| <p><code>operator.contains(obj)</code></p>
 
|-
 
| <p><code>operator.isSequenceType(obj)</code></p>
 
| <p><code>isinstance(obj, collections.abc.Sequence)</code></p>
 
|-
 
| <p><code>operator.isMappingType(obj)</code></p>
 
| <p><code>isinstance(obj, collections.abc.Mapping)</code></p>
 
|-
 
| <p><code>operator.isNumberType(obj)</code></p>
 
| <p><code>isinstance(obj, numbers.Number)</code></p>
 
|-
 
| <p><code>operator.repeat(obj, n)</code></p>
 
| <p><code>operator.mul(obj, n)</code></p>
 
|-
 
| <p><code>operator.irepeat(obj, n)</code></p>
 
| <p><code>operator.imul(obj, n)</code></p>
 
|}
 
</dd></dl>
 
 
; <span id="2to3fixer-paren"></span><code>paren</code>
 
: Add extra parenthesis where they are required in list comprehensions. For example, <code>[x for x in 1, 2]</code> becomes <code>[x for x in (1, 2)]</code>.
 
 
; <span id="2to3fixer-print"></span><code>print</code>
 
: Converts the <code>print</code> statement to the [[../functions#print|<code>print()</code>]] function.
 
 
; <span id="2to3fixer-raise"></span><code>raise</code>
 
: Converts <code>raise E, V</code> to <code>raise E(V)</code>, and <code>raise E, V, T</code> to <code>raise E(V).with_traceback(T)</code>. If <code>E</code> is a tuple, the translation will be incorrect because substituting tuples for exceptions has been removed in 3.0.
 
 
; <span id="2to3fixer-raw_input"></span><code>raw_input</code>
 
: Converts <code>raw_input()</code> to [[../functions#input|<code>input()</code>]].
 
 
; <span id="2to3fixer-reduce"></span><code>reduce</code>
 
: Handles the move of <code>reduce()</code> to [[../functools#functools|<code>functools.reduce()</code>]].
 
 
; <span id="2to3fixer-reload"></span><code>reload</code>
 
: Converts <code>reload()</code> to [[../importlib#importlib|<code>importlib.reload()</code>]].
 
 
; <span id="2to3fixer-renames"></span><code>renames</code>
 
: Changes <code>sys.maxint</code> to [[../sys#sys|<code>sys.maxsize</code>]].
 
 
; <span id="2to3fixer-repr"></span><code>repr</code>
 
: Replaces backtick repr with the [[../functions#repr|<code>repr()</code>]] function.
 
 
; <span id="2to3fixer-set_literal"></span><code>set_literal</code>
 
: Replaces use of the [[../stdtypes#set|<code>set</code>]] constructor with set literals. This fixer is optional.
 
 
; <span id="2to3fixer-standarderror"></span><code>standarderror</code>
 
: Renames <code>StandardError</code> to [[../exceptions#Exception|<code>Exception</code>]].
 
 
; <span id="2to3fixer-sys_exc"></span><code>sys_exc</code>
 
: Changes the deprecated <code>sys.exc_value</code>, <code>sys.exc_type</code>, <code>sys.exc_traceback</code> to use [[../sys#sys|<code>sys.exc_info()</code>]].
 
 
; <span id="2to3fixer-throw"></span><code>throw</code>
 
: Fixes the API change in generator's <code>throw()</code> method.
 
 
; <span id="2to3fixer-tuple_params"></span><code>tuple_params</code>
 
: Removes implicit tuple parameter unpacking. This fixer inserts temporary variables.
 
 
; <span id="2to3fixer-types"></span><code>types</code>
 
: Fixes code broken from the removal of some members in the [[../types#module-types|<code>types</code>]] module.
 
 
; <span id="2to3fixer-unicode"></span><code>unicode</code>
 
: Renames <code>unicode</code> to [[../stdtypes#str|<code>str</code>]].
 
 
; <span id="2to3fixer-urllib"></span><code>urllib</code>
 
: Handles the rename of [[../urllib#module-urllib|<code>urllib</code>]] and <code>urllib2</code> to the [[../urllib#module-urllib|<code>urllib</code>]] package.
 
 
; <span id="2to3fixer-ws_comma"></span><code>ws_comma</code>
 
: Removes excess whitespace from comma separated items. This fixer is optional.
 
 
; <span id="2to3fixer-xrange"></span><code>xrange</code>
 
: Renames <code>xrange()</code> to [[../stdtypes#range|<code>range()</code>]] and wraps existing [[../stdtypes#range|<code>range()</code>]] calls with [[../stdtypes#list|<code>list</code>]].
 
 
; <span id="2to3fixer-xreadlines"></span><code>xreadlines</code>
 
: Changes <code>for x in file.xreadlines()</code> to <code>for x in file</code>.
 
 
; <span id="2to3fixer-zip"></span><code>zip</code>
 
: Wraps [[../functions#zip|<code>zip()</code>]] usage in a [[../stdtypes#list|<code>list</code>]] call. This is disabled when <code>from future_builtins import zip</code> appears.
 
 
  
 
</div>
 
</div>
<div id="module-lib2to3" class="section">
 
 
<span id="lib2to3-2to3-s-library"></span>
 
== [[#module-lib2to3|<code>lib2to3</code>]] - 2to3's library ==
 
 
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/lib2to3/ Lib/lib2to3/]
 
 
<div class="deprecated">
 
 
<span class="versionmodified deprecated">3.10 版后已移除: </span>Python 3.9 will switch to a PEG parser (see <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-0617 '''PEP 617''']), and Python 3.10 may
 
include new language syntax that is not parsable by lib2to3's LL(1) parser.
 
The <code>lib2to3</code> module may be removed from the standard library in a future
 
Python version. Consider third-party alternatives such as [https://libcst.readthedocs.io/ LibCST] or
 
[https://parso.readthedocs.io/ parso].
 
 
  
 
</div>
 
</div>
<div class="admonition note">
+
<div class="clearer">
 
 
注解
 
 
 
The [[#module-lib2to3|<code>lib2to3</code>]] API should be considered unstable and may change
 
drastically in the future.
 
 
 
  
</div>
 
  
</div>
 
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:51的最新版本

2to3 - 自动 Python 2 到 3 代码翻译

2to3 是一个 Python 程序,它读取 Python 2.x 源代码并应用一系列 修复程序 将其转换为有效的 Python 3.x 代码。 标准库包含一组丰富的修复程序,可以处理几乎所有代码。 然而,2to3 支持库 lib2to3 是一个灵活的通用库,因此可以为 2to3 编写自己的修复程序。

使用 2to3

2to3 通常会作为脚本与 Python 解释器一起安装。 它也位于 Python 根目录的 Tools/scripts 目录中。

2to3 的基本参数是要转换的文件或目录列表。 递归遍历目录以获取 Python 源代码。

这是一个示例 Python 2.x 源文件,example.py

def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)

可以通过命令行中的 2to3 将其转换为 Python 3.x 代码:

$ 2to3 example.py

打印与原始源文件的差异。 2to3 还可以将所需的修改写回源文件。 (除非还给出了 -n,否则会备份原始文件。)使用 -w 标志启用回写更改:

$ 2to3 -w example.py

改造后的 example.py 长这样:

def greet(name):
    print("Hello, {0}!".format(name))
print("What's your name?")
name = input()
greet(name)

在整个翻译过程中保留注释和精确缩进。

默认情况下,2to3 运行一组 预定义的修复程序-l 标志列出了所有可用的修复程序。 可以使用 -f 给出一组明确的要运行的修复程序。 同样,-x 明确禁用了一个固定器。 以下示例仅运行 importshas_key 修复程序:

$ 2to3 -f imports -f has_key example.py

此命令运行除 apply 固定器之外的所有固定器:

$ 2to3 -x apply example.py

一些修复程序是 explicit,这意味着它们默认不运行,必须在命令行中列出才能运行。 在这里,除了默认的修复程序之外,还运行 idioms 修复程序:

$ 2to3 -f all -f idioms example.py

请注意传递 all 如何启用所有默认修复程序。

有时 2to3 会在您的源代码中找到需要更改的地方,但 2to3 无法自动修复。 在这种情况下, 2to3 将在文件的差异下方打印警告。 您应该解决警告以获得兼容的 3.x 代码。

2to3 还可以重构 doctest。 要启用此模式,请使用 -d 标志。 请注意,only doctests 将被重构。 这也不要求模块是有效的 Python。 例如,也可以使用此选项重构 reST 文档中类似 doctest 的示例。

-v 选项可以输出有关翻译过程的更多信息。

由于某些打印语句可以解析为函数调用或语句,因此 2to3 不能总是读取包含打印函数的文件。 当 2to3 检测到 from __future__ import print_function 编译器指令的存在时,它会修改其内部语法以将 print() 解释为函数。 也可以使用 -p 标志手动启用此更改。 使用 -p 在已转换其打印语句的代码上运行修复程序。 -e 也可用于使 exec() 成为一个函数。

-o--output-dir 选项允许指定用于写入已处理输出文件的备用目录。 -n 标志在使用它时需要,因为当不覆盖输入文件时,备份文件没有意义。

3.2.3 新功能: 增加了 -o 选项。


-W--write-unchanged-files 标志告诉 2to3 始终写入输出文件,即使文件不需要更改。 这对 -o 最有用,以便将整个 Python 源代码树复制并从一个目录转换到另一个目录。 这个选项意味着 -w 标志,否则它没有意义。

3.2.3 新功能: 增加了 -W 标志。


--add-suffix 选项指定要附加到所有输出文件名的字符串。 指定此选项时需要 -n 标志,因为在写入不同的文件名时不需要备份。 例子:

$ 2to3 -n -W --add-suffix=3 example.py

将导致写入名为 example.py3 的转换文件。

3.2.3 新功能: 增加了 --add-suffix 选项。


要将整个项目从一个目录树转换为另一种使用:

$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode

修理工

转换代码的每一步都封装在一个固定器中。 命令 2to3 -l 列出了它们。 正如上面所述的,每个都可以单独打开和关闭。 此处更详细地描述了它们。


lib2to3 - 2to3 的库

源代码: :source:`Lib/lib2to3/`



自 3.10 版起已弃用:Python 3.9 将切换到 PEG 解析器(请参阅 PEP 617),并且 Python 3.10 可能包含无法解析的新语言语法lib2to3 的 LL(1) 解析器。 lib2to3 模块可能会在未来的 Python 版本中从标准库中删除。 考虑第三方替代方案,例如 LibCSTparso


笔记

lib2to3 API 应该被认为是不稳定的,未来可能会发生巨大变化。