我想将 Python2 代码翻译成 Python 3.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))
为什么?
不知道这是否能解决你的问题,但你可以尝试修复你的缩进:
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"
我认为问题可能出在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 是 支持。
这就是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 代码。