简体   繁体   中英

python: how to get line text where exception occur, not line number

I am trying to use sys.excepthook

With below hook

def foo(type, value, traceback):
    # how to print the line that except occurs

sys.excepthook = foo

and use like below

$ python3
>>> text that cause error

How to define foo such that text that cause error being printed?

EDIT

Let me add the full story, to make it clear. (deserve downvotes? -) )

What I want is not print the line, is

  • get the line
  • if the line match some criterion, modify then exec

eg, if type

>>> import requests
>>> edit requests

get the line that exception occurs, ie, edit requests

then exec edit(find_file(request))

where edit() use subprocess.call() , find_file use inspect to find the file where an object being defined.

Yes, I know ipython magics, and use it regularlly. this time I am ask to how to define it.

You can use the modul traceback and the passed traceback object's tb_lineno attribute:

import sys
import traceback as tb

def foo(type, value, traceback):
    # how to print the line that except occurs
    print("The line where the exception occurs: {}".format(tb.linecache.getline(tb.extract_tb(sys.last_traceback)[0].filename, traceback.tb_lineno)))

sys.excepthook = foo

int("text")

Out:

The line where the exception occurs: int("text")

as the the line int("text") line raised an exeption.

We can use the traceback module to help us.

def foo(type, value, trace):
    print(trace.msg)

The traceback object will have lots of information about where the error occurred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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