-1

I want to translate Python2 code to Python 3.It is very simple,but it does not work

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"

I got this in terminal

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

Why?

cs95
  • 274,032
  • 76
  • 480
  • 537
MishaVacic
  • 1,514
  • 6
  • 21
  • 26

3 Answers3

2

Don't know if this will solve your problem, but you could try fixing your indentation:

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"
Luci
  • 392
  • 6
  • 13
0

I think the problem may be with MySQLdb. This package supports only upto 2.7 and won't support python 3. Currently MySQL-python 1.2.5 is the latest verions(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.

AKHIL MATHEW
  • 1,237
  • 2
  • 29
  • 59
0

This is what 2to3 does

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

I have changed furthermore

except MySQLdb.Error as e:

and now I have Python3 code.

MishaVacic
  • 1,514
  • 6
  • 21
  • 26