我正在导入一个在某些情况下会引发以下错误的模块: 运行时错误:pyparted 需要 root 访问权限
我知道我可以在导入之前检查 root 访问权限,但我想知道如何通过 try/except 语句捕获这种特定类型的错误以供将来引用。有什么方法可以区分此 RuntimeError 和其他可能引发的错误吗?
最佳答案
您可以检查异常的属性以区别于其他可能的 RuntimeError
异常。例如,如果它与预定义的消息文本不匹配,则重新引发错误。
try:
import pypatred
except RuntimeError,e:
if e.message == 'RuntimeError: pyparted requires root access':
return 'pyparted - no root access'
raise
当然,直接文本比较只是一个例子,您可以搜索包含的子串或正则表达式。
值得注意的是异常的.message
属性是deprecated starting with Python 2.6 .您可以在 .args
中找到文本,通常是 args[0]
。
... For 2.6, the
message
attribute is being deprecated in favor of theargs
attribute.
关于python - 仅捕获 Python 中的一些运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/825909/