-1

我想将 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))

为什么?

4

3 回答 3

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"
于 2017-07-25T12:07:12.357 回答
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。

于 2017-07-25T12:01:11.840 回答
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 代码。

于 2017-07-25T12:19:16.627 回答