python - 除了已加载的C库中的Python错误之外

标签 python exception error-handling

我有一段代码,它加载了一个库,但是死了。我已经用try/except传递将它包围了,但是它仍然死了。有谁知道如何克服错误并继续下面的打印语句:

      try: 
         library.load("test_data/polo.lib")
      except:
         pass

     defines = library.get_defines()
     print defines
     assert ( len(defines) == 3), "Make sure we have 3 defines"

我在library.load代码行之后立即得到的错误是:
scci18910> python test_001_library.py
Loading library test_data/polo.lib   
terminate called after throwing an instance of 'std::string'
Abort

最佳答案

您无法捕获异常,因为没有python异常被抛出。
但是您可以使用子流程绕过Abort:

创建文件list_defines.py:

library.load("test_data/polo.lib")
print(library.get_defines())

然后:
import subprocess

try:
    defines = parse_string_to_list_somehow(subprocess.check_output('python', '-c', 'list_defines.py'))
except CalledProcessError as e:
    print('Library defines list failed', e)
    defines = []

附言示例适用于python3

关于python - 除了已加载的C库中的Python错误之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751989/

相关文章:

python - 如何将一个 csv (txt) 文件中的记录与另一个 csv (txt) 文件中的记录进行比较,并根据它们的比较计算出一个数字?

Python - For 循环没有启动(二十一点游戏)

python - 使用词云提高分辨率并删除空白边框

c++ - 如何确定 catch (...) block 中的当前异常?

python - Django可疑操作

c - 如果 posix 关闭调用失败怎么办?

python - 在 Python 中从 json 对象创建连接字符串

java - 动态方法中的 InvokingTargetException

python - Flask RestPlus : how to catch all exceptions and output the original error

php - 拉拉维尔 5.7 : Trying to get property 'role' of non-object