代码之家  ›  专栏  ›  技术社区  ›  MishaVacic

自动Python翻译2to3错误

  •  -1
  • MishaVacic  · 技术社区  · 9 年前

    我想把Python2代码翻译成Python3。它非常简单,但不起作用

    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 回复  |  直到 8 年前
        1
  •  2
  •   Luci    9 年前

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

    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"
    
        2
  •  0
  •   Akhil Mathew    9 年前

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

    MySQL版本3.23到5.5以及Python-2.4到2.7目前正在使用

        3
  •  0
  •   MishaVacic    9 年前

    这就是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:
    

    推荐文章