相当于Tcl "catch"的Python,带有用于错误输出的变量



在 Tcl 中,您可以使用 catch 命令将错误输出发送到变量,如下所示:

% catch {eval exec bogomips &} outage
1
% puts $outage
couldn't execute "bogomips": no such file or directory

在 Python 中(我仍然是初学者),我知道try基本上等同于 catch ,但我没有看到如何在变量中捕获错误输出。这可以在Python中完成而无需诉诸子进程,Popen等吗?如果是这样,如何?

使用一个或多个except子句,捕获相应的异常类型:

def something(x):
    if type(x) != int:
        raise TypeError("Expected an int, but was %s" % str(type(x)))
    if x == 0:
        raise ValueError("Zero not allowed")
try:
    something(0)
except ValueError as e:
    print 'got a value error:', e
except TypeError as e:
     print 'got a type error:', e

(Python 2 代码,但 Python 3 在这方面是一样的。

以下是有关错误和异常的文档:https://docs.python.org/2.7/tutorial/errors.html

捕获外部程序的错误:

import subprocess
print(subprocess.Popen("dir c:\dosent\exists", shell=True, stderr=subprocess.PIPE).stderr.read().decode('cp866'))

最新更新