简体   繁体   English

python中的堆栈跟踪和异常处理

[英]stack trace and exception handling in python

I want to design a python program that handles exceptions in other programs , I also want this to access the stack trace in python . 我想设计一个处理其他程序中异常的python程序,我也希望它能够访问python中的堆栈跟踪。 I am new t python development but am willing to learn but I do not have a direction on where to proceed . 我是python的新开发人员,但愿意学习,但是我没有前进方向的指导。 Could somebody please point me to a direction / resources that I could follow and maybe develop these skills , specifically what I should be learning to achieve my goal. 有人可以为我指出一个可以遵循并可能发展这些技能的方向/资源,尤其是我应该学习的实现目标的方法。

I want to develop this on python 2.7 我想在python 2.7上开发

Thank you for your responses. 谢谢你的回复。

EDIT : by handling exceptions , I just want to know what exception occured . 编辑:通过处理异常,我只想知道发生了什么异常。 Like in Java with try catch blocks where you can print out the stack trace and see if it is an arithmetic / array out of bounds error 就像在Java中使用try catch块一样,您可以在其中打印出堆栈跟踪并查看它是否是算术/数组超出范围错误

Hi I was also thinking of something on this line something like 嗨,我也在想这条线上的东西

  try

 (Execute python program here)  // ie import this program 

 except : 1st exception
 except : 2nd exception
 .
 .
 etc

I know how to read from a file , but an unsure if this is correct for just executing a program written by somebody else? 我知道如何从文件中读取内容,但是不确定仅执行其他人编写的程序是否正确?

Take a look at the traceback module. 看一下追溯模块。 It formats and prints stack traces. 它格式化并打印堆栈跟踪。 You can use this is a top-level exception handler. 您可以使用这是顶级异常处理程序。

import sys
import traceback

try:
    do_something()
except:
    ex, val, tb = sys.exc_info()
    traceback.print_exception(ex, val, tb)

Python itself essentially does this on any uncaught excepton, then exits. Python本身实际上对任何未捕获的异常执行此操作,然后退出。

I am a little confused about your question; 我对你的问题有些困惑; if you are only running other python code this will be automatic. 如果您仅运行其他python代码,这将是自动的。 You don't need to read any files, just import the python modules you want to use and call their functions. 您无需读取任何文件,只需导入要使用的python模块并调用它们的函数即可。 When these throw exceptions they will simply end up in your code and you can deal with them as you see fit, taking into account best practice regarding exception ahndling of course. 当这些抛出异常时,它们只会最终出现在您的代码中,并且您可以根据需要处理它们,并考​​虑到有关异常防范的最佳实践。

For a quick tutorial on python exceptions look here . 有关python异常的快速教程,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM