How do I convert this code from Python 2 to to Python 3:
except ET.XMLSyntaxError, log:
#This exception raised if the file has parse errors in it
logging.error("XSD: " log.message)
raise SyntaxError, log.message
I'm not actually sure what the raise
line is doing. I've already replaced
except ET.XMLSyntaxError, log:
with
except ET.XMLSyntaxError as log:
Background: I upgraded my system to python 3.7 and our build is not working with a number of Python scripts though it might be faster to update our scripts to Python 3 than revert my ubuntu environment.
CodePudding user response:
The immediate fix for you is this:
raise SyntaxError(log.message)
If you have a lot of Python 2.x scripts, I'd recommend using the 2to3
tool to have it translate from python 2.x to 3.x. The documentation even calls out the raise
change you're asking for here:
raise
Converts
raise E, V
toraise E(V)
, andraise E, V, T
toraise E(V).with_traceback(T)
. IfE
is atuple
, the translation will be incorrect because substituting tuples for exceptions has been removed in 3.0.
Here's a snippet with a piece of code that's in Python 2.x exception format that we'll run 2to3
on:
import logging
try:
print "hello"
except Exception, log:
#This exception raised if the file has parse errors in it
logging.error("XSD: " log.message)
raise Exception, log.message
Running 2to3
# As needed: pip install 2to3
> 2to3 code.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 code.py
--- code.py (original)
code.py (refactored)
@@ -1,8 1,8 @@
import logging
try:
- print "hello"
-except Exception, log:
print("hello")
except Exception as log:
#This exception raised if the file has parse errors in it
logging.error("XSD: " log.message)
- raise Exception, log.message
raise Exception(log.message)
RefactoringTool: Files that need to be modified:
RefactoringTool: code.py