简体   繁体   中英

Can I modify what pdb prints when an Exception is thrown?

I run:

python -m pdb script_that_throws.py

When the script throws, say because of a failed assertion, pdb prints the entire stack trace + some pointless boilerplate text:

Traceback (most recent call last):
  File "/usr/lib/python3.6/pdb.py", line 1667, in main
    pdb._runscript(mainpyfile)
  File "/usr/lib/python3.6/pdb.py", line 1548, in _runscript
    self.run(statement)
  File "/usr/lib/python3.6/bdb.py", line 434, in run
    exec(cmd, globals, locals)
  File "<string>", line 1, in <module>
  [... many lines of stack trace omitted for brevity ...]
  File "/path/to/script_that_throws.py", line 26, in _ul
    assert v.keys() == self._expected_keys
AssertionError
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /path/to/script_that_throws.py(26)_ul()
-> assert v.keys() == self._expected_keys
(Pdb)

I would like for Python to only show:

AssertionError
> /path/to/script_that_throws.py(26)_ul()
-> assert v.keys() == self._expected_keys
(Pdb)

Is there a way to achieve that?

There is a good and a bad answer.

The good one. Certainly, you can suppress these messages.

And now the bad answer comes into play.

You have to change cpython source code, and recompile it.

This is not so hard as it sounds at first, especially, as pdb is a Python module, no C knowledge required.

This is the important part of the source code:

https://github.com/python/cpython/blob/master/Lib/pdb.py#L1718-L1725

There is excellent documentation out there on how to compile Python: https://docs.python.org/3/using/unix.html#building-python

Also, Anthony Shaw just published a book which gives a good introduction on how to work with cpython , the C implementation of the Python language.

Just in case you expected a different kind of answer, no, there is no configuration option for PDB to suppress these kind of messages.

It would be nice to know what script_that_throws.py does. Have you tried using try and except in your script? This can help you handle the pdb exceptions to print whatever you want. Like so:

n = input("age ")
try:
    print(int(n))
except ValueError:
    print("error")

You can also manually raise your own exception as shown in this thread: Manually raising (throwing) an exception in Python

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