PyScripter - 使用 2to3 外部命令將 Python2 程式碼轉換成 Python3 相容
由於 Python2 與 Python3 並不相容,加上 Python2 版本不一定會繼續持續演進下去。
所以,還是蠻多人還是會想把 Python2 的程式碼轉換到 Python3 上,隨著 Python3 的版本演進,能夠持續更新。
在 Python2 與 Python3 的差異請參考:「Moving from Python 2 to Python 3」Pdf 檔案,可以自行比對。
另外,下載安裝 Python 3.x 版本後,在 c:\Python3x\Tools\Scripts\ 目錄下,其實官方有提供工具:2to3.py
該工具可以幫助我們轉換 Python2 程式碼至 Python3,或是列出相關轉換前後的差異。
參考:「25.4. 2to3 - Automated Python 2 to 3 code translation」文章說明…
或是在命令列下輸入 python32 2to3.py --help,就可以看到詳細的使用方式:
C:\Python32\Tools\Scripts>python32 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
.py3 files.
我們已經知道 Python3 的 2to3.py 如何使用,現在我們就在 PyScripter 中設定外部命令來轉換程式碼:
1. 打開 PyScripter 3.2:
2. Tools –> Configure Tools 開啟設定:
3. 點「Add」進行新增
4. 設定 External Tools Properties:
(1) Name:2to3 (可自行命名)
(2) Application:$[PythonExe-Short] (就是 Python32 的執行檔位置)
(3) Parameters:$[PythonDir-Short]Tools\Scripts\2to3.py -w $[ActiveDoc-Short]
( $[PythonDir-Short] 是 Pthon32 的安裝目錄,-w 是 2to3.py 所需要參數表示寫入檔案,$[ActiveDoc-Short] 是目前程式碼檔案位置)
(4) Context:Active Python file (我們轉換的目標是編輯中的 Python 檔案)
(5) Capture Output 打勾 (補抓 2to3.py 的輸出訊息)
以下是 艾小克撰寫 Python2 範例程式碼如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import random
def greet(name):
print 'Hello, number %s!' % name
# main
name = raw_input('Enter your name:')
greet(name)
ans = random.randint(0, 10)
value = raw_input('Enter your numebr(0-9):')
while True:
if int(value) <> ans:
print 'Worng! Please guess it angin!'
value = raw_input('Enter your numebr(0-9):')
else:
print 'Correct! Answer is %d', value
break
透過 Tools –> 2to3 來執行轉換:
透過轉換後程式碼如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import random
def greet(name):
print('Hello, number %s!' % name)
# main
name = input('Enter your name:')
greet(name)
ans = random.randint(0, 10)
value = input('Enter your numebr(0-9):')
while True:
if int(value) != ans:
print('Worng! Please guess it angin!')
value = input('Enter your numebr(0-9):')
else:
print('Correct! Answer is %d', value)
break
參考畫面:
因為我們有設定 Capture Output,所以透過 Output 頁籤來檢視轉換的情況:
接下來,我們就可以再次使用 Ctrl + F9 執行程式碼,看看是否能在 Python3 執行囉…