如何追溯函数内引发异常的原因?
How to trace back the cause of an exception raised within a function?
(这是 post Python try/except: Showing the cause of the error after displaying my variables 的后续问题。)
我有以下 script.py
:
import traceback
def process_string(s):
"""
INPUT
-----
s: string
Must be convertable to a float
OUTPUT
------
x: float
"""
# validate that s is convertable to a float
try:
x = float(s)
return x
except ValueError:
print
traceback.print_exc()
if __name__ == '__main__':
a = process_string('0.25')
b = process_string('t01')
c = process_string('201')
执行 script.py
后,在终端 window 中打印以下消息:
Traceback (most recent call last):
File "/home/user/Desktop/script.py", line 20, in process_string
x = float(s)
ValueError: could not convert string to float: t01
请问是否有办法让 traceback.print_exc()
也能在终端中打印 window if-main 中的哪条指令引发了 try-except 子句捕获的异常?
这个呢?
import traceback
def process_string(s):
"""
INPUT
-----
s: string
Must be convertible to a float
OUTPUT
------
x: float
"""
return float(s)
if __name__ == '__main__':
try:
a = process_string('0.25')
b = process_string('t01')
c = process_string('201')
except ValueError:
print
traceback.print_exc()
(这是 post Python try/except: Showing the cause of the error after displaying my variables 的后续问题。)
我有以下 script.py
:
import traceback
def process_string(s):
"""
INPUT
-----
s: string
Must be convertable to a float
OUTPUT
------
x: float
"""
# validate that s is convertable to a float
try:
x = float(s)
return x
except ValueError:
print
traceback.print_exc()
if __name__ == '__main__':
a = process_string('0.25')
b = process_string('t01')
c = process_string('201')
执行 script.py
后,在终端 window 中打印以下消息:
Traceback (most recent call last):
File "/home/user/Desktop/script.py", line 20, in process_string
x = float(s)
ValueError: could not convert string to float: t01
请问是否有办法让 traceback.print_exc()
也能在终端中打印 window if-main 中的哪条指令引发了 try-except 子句捕获的异常?
这个呢?
import traceback
def process_string(s):
"""
INPUT
-----
s: string
Must be convertible to a float
OUTPUT
------
x: float
"""
return float(s)
if __name__ == '__main__':
try:
a = process_string('0.25')
b = process_string('t01')
c = process_string('201')
except ValueError:
print
traceback.print_exc()