1

Running some code with Python3 reports the below error:

$ python3 report.py --regions ap-southeast-2 --file file.csv
  File "report.py", line 51
    except Exception, e:
                    ^
SyntaxError: invalid syntax

Research indicates that this deprecated syntax. I have found conflicting information on how I may fix this.

I have tried to engage python3 syntax, which I believe would be to switch

   try:
        f = file(filepath, 'wt')
    except Exception, e:
        f = None
        sys.stderr.write ('Could not open file %s. reason: %s\n' % (filepath, e))

To:

  try:
       f = file(filepath, 'wt')
except:
       f = None
       sys.stderr.write ('Could not open file %s. reason: %s\n' % (filepath, e))

What happens then is that I get errors relating to the "e" being missing... so I'm unsure how best and easiest to resolve the syntax issues between the two versions. Can you help or advise? Thanks!

1
  • 2
    try except Exception as e: Commented Jul 17, 2020 at 5:26

1 Answer 1

1

If you really want a method that is compatible for both Python2 and Python3,

Then try something like this:

 import sys
 try:
    ### your filepath code goes here or any other code
 except Exception:
    tb, err = sys.exc_info()[:2]
    print(err)

Using exc_info() here is good as it provides you with a tuple of information on what the error and the traceback to that faulting code, specifically the (type, value, traceback). In this case, you are getting back the traceback and the error (value).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.