自动 Python 翻译 2to3 错误

Automated Python translation 2to3 error

我想把Python2代码翻译成Python3.It很简单,但是不行

import sys
import MySQLdb
import Cookbook

try:
 conn = Cookbook.connect ()
print "Connected"
 except MySQLdb.Error, e:
 print "Cannot connect to server"
 print "Error code:", e.args[0]
 print "Error message:", e.args[1]
 sys.exit (1)

conn.close ()
print "Disconnected"

我在终端中得到了这个

2to3 harness.py
RefactoringTool: Skipping optional fixer: buffer
RefactoringTool: Skipping optional fixer: idioms
RefactoringTool: Skipping optional fixer: set_literal
RefactoringTool: Skipping optional fixer: ws_comma
RefactoringTool: Can't parse harness.py: ParseError: bad input: type=1, value='print', context=('', (9, 0))
RefactoringTool: No files need to be modified.
RefactoringTool: There was 1 error:
RefactoringTool: Can't parse harness.py: ParseError: bad input: type=1, value='print', context=('', (9, 0))

为什么?

我认为问题可能出在 MySQLdb 上。这个包只支持到 2.7,不支持 python 3. 目前 MySQL-python 1.2.5 是最新版本(25-07-2017)

MySQL versions 3.23 through 5.5 and Python-2.4 through 2.7 are currently supported. Python-3.0 will be supported in a future release. PyPy is supported.

不知道这是否能解决您的问题,但您可以尝试修复缩进:

import sys
import MySQLdb
import Cookbook

try:
    conn = Cookbook.connect ()
    print "Connected"
except MySQLdb.Error, e:
    print "Cannot connect to server"
    print "Error code:", e.args[0]
    print "Error message:", e.args[1]
    sys.exit (1)

conn.close ()
print "Disconnected"

这就是 2to3 所做的

2to3 new.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 new.py
--- new.py  (original)
+++ new.py  (refactored)
@@ -4,12 +4,12 @@

 try:
     conn = Cookbook.connect ()
-    print "Connected"
-except MySQLdb.Error, e:
-    print "Cannot connect to server"
-    print "Error code:", e.args[0]
-    print "Error message:", e.args[1]
+    print("Connected")
+except MySQLdb.Error as e:
+    print("Cannot connect to server")
+    print("Error code:", e.args[0])
+    print("Error message:", e.args[1])
     sys.exit (1)

 conn.close ()
-print "Disconnected"
+print("Disconnected")
RefactoringTool: Files that need to be modified:
RefactoringTool: new.py

我又变了

except MySQLdb.Error as e:

现在我有了 Python3 代码。