python有它的错误报告消息,如$!在perl

rai*_*zwr 5 python perl

我想知道python是否有错误报告消息相当于$!在perl?任何能给我答案的人都将不胜感激.

添加:

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

当Exception发生时,我得到了类似的东西.如果我应用try和catch块,我可以捕获它并使用sys.exit(message)来记录消息.但是,我是否有机会获得字符串SyntaxError:无效语法并将其放入消息中

Kei*_*ith 8

Python通常使用异常来报告错误.如果某些OS操作返回错误代码,则会引发您在try-except块中捕获的异常.对于OS操作,即OSError.errno包含在异常实例中.

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])
Run Code Online (Sandbox Code Playgroud)

输出:

[Errno 2] No such file or directory: 'xxx'
2
Run Code Online (Sandbox Code Playgroud)

  • 错误不是一个元组.它是OSError类的一个实例,与大多数异常类一样,它支持索引. (3认同)

Cam*_*ron 5

据我所知,没有直接的等价物.

Python倾向于支持抛出异常,这使得您可以以类似的方式访问错误消息,尽管通过异常对象而不是特殊变量.