自动Python翻译2to3错误

时间:2017-07-25 11:55:05

标签: python python-2to3

我想将Python2代码翻译成Python 3.它非常简单,但它不起作用

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))

为什么?

3 个答案:

答案 0 :(得分:2)

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

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"

答案 1 :(得分:0)

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

  

MySQL版本3.23到5.5和Python-2.4到2.7目前   支持的。未来版本将支持Python-3.0。 PyPy是   支撑。

答案 2 :(得分:0)

这是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代码。