Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does python has its error report message like $! in perl

Tags:

python

perl

I am wondering if python has its error report message equivalent to $! in perl ? Anyone who could give me an answer will be greatly appreciated.

Added:

example% ./test
File "./test", line 7
  test1 = test.Test(dir)
  ^
SyntaxError: invalid syntax

When Exception occurs, I got something like this. If I apply try and catch block, I can catch it and use sys.exit(message) to log the message. But, is there any chance that I can get the string SyntaxError: invalid syntax and put it in message

like image 984
rain zwr Avatar asked Apr 24 '12 04:04

rain zwr


2 Answers

Python generally uses exceptions to report errors. If some OS operation returns an error code, it raises an exception that you catch in a try-except block. For OS operations, that is OSError. The errno is contained in the exception instance.

from __future__ import print_function
import os

try:
        os.stat("xxx")
except OSError as err:
        print (err)
        # The "err" object is on instance of OSError. It supports indexing, with the first element as the errno value.
        print(err[0])

Output:

[Errno 2] No such file or directory: 'xxx'
2
like image 89
Keith Avatar answered Oct 22 '22 10:10

Keith


There is no direct equivalent, as far as I'm aware.

Python tends to favour throwing exceptions instead, which lets you access the error message afterwards in a similar manner, albeit through the exception object instead of a special variable.

like image 24
Cameron Avatar answered Oct 22 '22 10:10

Cameron