Python2到Python3代碼的轉換工具2to3.py

之前一直遇到Python2代碼轉到Python3代碼的需求,最近才知道Python官方就有一個轉換工具:2to3.py。 
無論是Python官網下載安裝的python還是利用Anaconda安裝,目錄都在{Python_HOME}\Tools\scripts裏面。運行 2to3.py 腳本,打印如下:

python 2to3.py --help
Usage: 2to3 [options] file|dir ...

Options:
  -h, --help            show this help message and exit
  -d, --doctests_only   Fix up doctests only
  -f FIX, --fix=FIX     Each FIX specifies a transformation; default: all
  -j PROCESSES, --processes=PROCESSES
                        Run 2to3 concurrently
  -x NOFIX, --nofix=NOFIX
                        Prevent a transformation from being run
  -l, --list-fixes      List available transformations
  -p, --print-function  Modify the grammar so that print() is a function
  -v, --verbose         More verbose logging
  --no-diffs            Don't show diffs of the refactoring
  -w, --write           Write back modified files
  -n, --nobackups       Don't write backups for modified files
  -o OUTPUT_DIR, --output-dir=OUTPUT_DIR
                        Put output files in this directory instead of
                        overwriting the input files.  Requires -n.
  -W, --write-unchanged-files
                        Also write files even if no changes were required
                        (useful with --output-dir); implies -w.
  --add-suffix=ADD_SUFFIX
                        Append this string to all output filenames. Requires
                        -n if non-empty.  ex: --add-suffix='3' will generate
  • 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

假設我在E:\pycode目錄下有個py2.py文件,代碼如下:

print 'test'
  • 1

我想把上面的代碼改成python3版本的。、 
應該先cmd進入{Python_HOME}\Tools\scripts目錄,然後執行如下:

python 2to3.py -w E:\pycode\py2.py
  • 1

執行整個流程如下:

D:\Anaconda3\Tools\scripts>python 2to3.py -w E:\pycode\py2.py
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Refactored E:\pycode\py2.py
--- E:\pycode\py2.py    (original)
+++ E:\pycode\py2.py    (refactored)
@@ -1 +1 @@
-print 'test'
+print('test')
RefactoringTool: Files that were modified:
RefactoringTool: E:\pycode\py2.py
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

然後我們可以看到,在E:\pycode目錄下多了一個py2.py.bak文件,這是原來的py2.py文件備份。 
查看py2.py,內容已被修改爲:

print('test')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章