gpt4 book ai didi

python - 拦截来自第三方代码的消息

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:27 24 4
gpt4 key购买 nike

我正在编写一个使用 GDAL 中的第 3 方模块的 Python 脚本。发生错误时,GDAL 函数不会引发异常,但会向 stdout 发送消息。一般来说,GDAL 函数发生的错误并不保证停止该进程,而且我不需要知道发生的错误。

有没有办法可以在控制台打印之前拦截发送到 stdout 的消息? GDAL 消息会干扰我在自己的代码中提供的消息。

最佳答案

"Python Gotchas" 中所述,您可以使用 gdal.UseExceptions() 打开异常,例如:

from osgeo import gdal

dsrc = gdal.Open('nonexist')
# ... silence

gdal.UseExceptions()

dsrc = gdal.Open('nonexist')
# Traceback (most recent call last):
# File "<interactive input>", line 1, in <module>
# RuntimeError: `nonexist' does not exist in the file system,
# and is not recognised as a supported dataset name.

您始终可以使用 try except block 获取实际的错误消息字符串:

try:
dsrc = gdal.Open('nonexist')
except RuntimeError as e:
print(str(e))

它将打印错误消息:

`nonexist' does not exist in the file system, and is not recognised as a supported dataset name.

关于python - 拦截来自第三方代码的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19192003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com