1. 程式人生 > >Python2轉Python3

Python2轉Python3

經常會遇到一些python2的程式碼,但是需要python3 來執行,官方提供了一個便捷的方式,在我們的python安裝目錄下,
{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

現在我的python2指令碼在D:\code目錄下有個hello2.py檔案,程式碼如下:

print ‘hello’

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

python 2to3.py -w D:\code\hello2.py

執行整個流程如下:

D:\Anaconda3\Tools\scripts>python 2to3.py -w D:\code\hello2.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 D:\code\hello2.py
--- D:\code\hello2.py (original)
+++ D:\code\hello2.py  (refactored)
@@ -1 +1 @@
-print 'hello'
+print('hello')
RefactoringTool: Files that were modified:
RefactoringTool: D:\code\hello2.py

然後我們可以看到,在D:\code目錄下多了一個hello2.py.bak檔案,這是原來的hello2.py檔案備份。
檢視hello2.py,內容已被修改為:

print(‘hello’)