forked from pdbpp/pdbpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdb.py
More file actions
1675 lines (1405 loc) · 55.9 KB
/
pdb.py
File metadata and controls
1675 lines (1405 loc) · 55.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
pdb++, a drop-in replacement for pdb
====================================
This module extends the stdlib pdb in numerous ways: look at the README for
more details on pdb++ features.
"""
from __future__ import print_function
import sys
import os.path
import inspect
import code
import codecs
import contextlib
import types
import traceback
import subprocess
import threading
import pprint
import re
import signal
from collections import OrderedDict
import fancycompleter
import six
from fancycompleter import Color, Completer, ConfigurableClass
__author__ = 'Antonio Cuni <anto.cuni@gmail.com>'
__url__ = 'http://github.com/antocuni/pdb'
__version__ = fancycompleter.LazyVersion('pdbpp')
try:
from inspect import signature # Python >= 3.3
except ImportError:
try:
from funcsigs import signature
except ImportError:
def signature(obj):
return ' [pip install funcsigs to show the signature]'
# If it contains only _, digits, letters, [] or dots, it's probably side
# effects free.
side_effects_free = re.compile(r'^ *[_0-9a-zA-Z\[\].]* *$')
RE_COLOR_ESCAPES = re.compile("(\x1b.*?m)*")
if sys.version_info < (3, ):
from io import BytesIO as StringIO
else:
from io import StringIO
local = threading.local()
local.GLOBAL_PDB = None
local._pdbpp_completing = False
def __getattr__(name):
"""Backward compatibility (Python 3.7+)"""
if name == "GLOBAL_PDB":
return local.GLOBAL_PDB
raise AttributeError
def import_from_stdlib(name):
import code # arbitrary module which stays in the same dir as pdb
result = types.ModuleType(name)
stdlibdir, _ = os.path.split(code.__file__)
pyfile = os.path.join(stdlibdir, name + '.py')
with open(pyfile) as f:
src = f.read()
co_module = compile(src, pyfile, 'exec', dont_inherit=True)
exec(co_module, result.__dict__)
return result
pdb = import_from_stdlib('pdb')
def rebind_globals(func, newglobals):
newfunc = types.FunctionType(func.__code__, newglobals, func.__name__,
func.__defaults__, func.__closure__)
if sys.version_info >= (3, ):
newfunc.__annotations__ = func.__annotations__
newfunc.__kwdefaults__ = func.__kwdefaults__
return newfunc
class DefaultConfig(object):
prompt = '(Pdb++) '
highlight = True
sticky_by_default = False
bg = 'dark'
use_pygments = True
colorscheme = None
use_terminal256formatter = None # Defaults to `"256color" in $TERM`.
editor = None # Autodetected if unset.
stdin_paste = None # for emacs, you can use my bin/epaste script
truncate_long_lines = True
exec_if_unfocused = None
disable_pytest_capturing = False
encodings = ('utf-8', 'latin-1')
enable_hidden_frames = True
show_hidden_frames_count = True
line_number_color = Color.turquoise
filename_color = Color.yellow
current_line_color = "39;49;7" # default fg, bg, inversed
show_traceback_on_error = True
show_traceback_on_error_limit = None
# Default keyword arguments passed to ``Pdb`` constructor.
default_pdb_kwargs = {
}
def setup(self, pdb):
pass
def before_interaction_hook(self, pdb):
pass
def setbgcolor(line, color):
# hack hack hack
# add a bgcolor attribute to all escape sequences found
import re
setbg = '\x1b[%sm' % color
regexbg = '\\1;%sm' % color
result = setbg + re.sub('(\x1b\\[.*?)m', regexbg, line) + '\x1b[00m'
if os.environ.get('TERM') == 'eterm-color':
# it seems that emacs' terminal has problems with some ANSI escape
# sequences. Eg, 'ESC[44m' sets the background color in all terminals
# I tried, but not in emacs. To set the background color, it needs to
# have also an explicit foreground color, e.g. 'ESC[37;44m'. These
# three lines are a hack, they try to add a foreground color to all
# escape sequences wich are not recognized by emacs. However, we need
# to pick one specific fg color: I choose white (==37), but you might
# want to change it. These lines seems to work fine with the ANSI
# codes produced by pygments, but they are surely not a general
# solution.
result = result.replace(setbg, '\x1b[37;%dm' % color)
result = result.replace('\x1b[00;%dm' % color, '\x1b[37;%dm' % color)
result = result.replace('\x1b[39;49;00;', '\x1b[37;')
return result
CLEARSCREEN = '\033[2J\033[1;1H'
def lasti2lineno(code, lasti):
import dis
linestarts = list(dis.findlinestarts(code))
linestarts.reverse()
for i, lineno in linestarts:
if lasti >= i:
return lineno
return 0
class Undefined:
def __repr__(self):
return '<undefined>'
undefined = Undefined()
class PdbMeta(type):
def __call__(cls, *args, **kwargs):
"""Reuse an existing instance with ``pdb.set_trace()``."""
global_pdb = getattr(local, "GLOBAL_PDB", None)
in_interaction = global_pdb and global_pdb._in_interaction
use_global_pdb = kwargs.pop("use_global_pdb", not in_interaction)
frame = sys._getframe().f_back
called_for_set_trace = False
while frame:
if (frame.f_code.co_name == "set_trace"
and frame.f_back
and "set_trace" in frame.f_back.f_code.co_names):
called_for_set_trace = frame
break
frame = frame.f_back
same_class = global_pdb and cls.consider_as_same_class(global_pdb, cls)
if use_global_pdb and same_class and called_for_set_trace:
if hasattr(global_pdb, "botframe"):
# Do not stop while tracing is active (in _set_stopinfo).
# But skip it with instances that have not called set_trace
# before.
# Excplicitly unset tracing function always (with breakpoints).
sys.settrace(None)
global_pdb.set_continue()
global_pdb._set_trace_use_next = True
return global_pdb
obj = cls.__new__(cls)
if called_for_set_trace:
kwargs.setdefault("start_filename", called_for_set_trace.f_code.co_filename)
kwargs.setdefault("start_lineno", called_for_set_trace.f_lineno)
set_global_pdb = kwargs.pop("set_global_pdb", use_global_pdb)
obj.__init__(*args, **kwargs)
if set_global_pdb:
local.GLOBAL_PDB = obj
return obj
@classmethod
def consider_as_same_class(cls, obj, C):
if isinstance(obj, C):
return True
if sys.version_info < (3, 3):
return inspect.getsourcelines(obj.__class__) == inspect.getsourcelines(C)
return C.__qualname__ == obj.__class__.__qualname__
@six.add_metaclass(PdbMeta)
class Pdb(pdb.Pdb, ConfigurableClass, object):
DefaultConfig = DefaultConfig
config_filename = '.pdbrc.py'
disabled = False
fancycompleter = None
_in_interaction = False
def __init__(self, *args, **kwds):
self.ConfigFactory = kwds.pop('Config', None)
self.start_lineno = kwds.pop('start_lineno', None)
self.start_filename = kwds.pop('start_filename', None)
self.config = self.get_config(self.ConfigFactory)
self.config.setup(self)
if self.config.disable_pytest_capturing:
self._disable_pytest_capture_maybe()
kwargs = self.config.default_pdb_kwargs.copy()
kwargs.update(**kwds)
super(Pdb, self).__init__(*args, **kwargs)
self.prompt = self.config.prompt
self.display_list = {} # frame --> (name --> last seen value)
self.sticky = self.config.sticky_by_default
self.first_time_sticky = self.sticky
self.sticky_ranges = {} # frame --> (start, end)
self.tb_lineno = {} # frame --> lineno where the exception raised
self.history = []
self.show_hidden_frames = False
self.hidden_frames = []
self.stdout = self.ensure_file_can_write_unicode(self.stdout)
def ensure_file_can_write_unicode(self, f):
# Wrap with an encoder, but only if not already wrapped
if (not hasattr(f, 'stream')
and getattr(f, 'encoding', False)
and f.encoding.lower() != 'utf-8'):
f = codecs.getwriter('utf-8')(getattr(f, 'buffer', f))
return f
def _disable_pytest_capture_maybe(self):
try:
import py.test
# Force raising of ImportError if pytest is not installed.
py.test.config
except (ImportError, AttributeError):
return
try:
capman = py.test.config.pluginmanager.getplugin('capturemanager')
capman.suspendcapture()
except KeyError:
pass
except AttributeError:
# Newer pytest with support ready, or very old py.test for which
# this hack does not work.
pass
def interaction(self, frame, traceback):
self._in_interaction = True
try:
return self._interaction(frame, traceback)
finally:
self._in_interaction = False
def _interaction(self, frame, traceback):
# Restore the previous signal handler at the Pdb prompt.
if getattr(pdb.Pdb, '_previous_sigint_handler', None):
try:
signal.signal(signal.SIGINT, pdb.Pdb._previous_sigint_handler)
except ValueError: # ValueError: signal only works in main thread
pass
else:
pdb.Pdb._previous_sigint_handler = None
ret = self.setup(frame, traceback)
if ret:
# no interaction desired at this time (happens if .pdbrc contains
# a command like "continue")
self.forget()
return
if self.config.exec_if_unfocused:
self.exec_if_unfocused()
self.print_stack_entry(self.stack[self.curindex])
self.print_hidden_frames_count()
with self._custom_completer():
self.config.before_interaction_hook(self)
# Use _cmdloop on py3 which catches KeyboardInterrupt.
if hasattr(self, '_cmdloop'):
self._cmdloop()
else:
self.cmdloop()
self.forget()
@contextlib.contextmanager
def _custom_completer(self):
if not self.fancycompleter:
self.fancycompleter = fancycompleter.setup()
readline_ = self.fancycompleter.config.readline
old_completer = readline_.get_completer()
readline_.set_completer(self.complete)
self._lastcompstate = [None, 0]
try:
yield
finally:
readline_.set_completer(old_completer)
def print_hidden_frames_count(self):
n = len(self.hidden_frames)
if n and self.config.show_hidden_frames_count:
plural = n > 1 and "s" or ""
print(
" %d frame%s hidden (try 'help hidden_frames')" % (n, plural),
file=self.stdout,
)
def exec_if_unfocused(self):
import os
import wmctrl
term = os.getenv('TERM', '')
try:
winid = int(os.getenv('WINDOWID'))
except (TypeError, ValueError):
return # cannot find WINDOWID of the terminal
active_win = wmctrl.Window.get_active()
if not active_win or (int(active_win.id, 16) != winid) and \
not (active_win.wm_class == 'emacs.Emacs' and term.startswith('eterm')):
os.system(self.config.exec_if_unfocused)
def setup(self, frame, tb):
ret = super(Pdb, self).setup(frame, tb)
if not ret:
while tb:
lineno = lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti)
self.tb_lineno[tb.tb_frame] = lineno
tb = tb.tb_next
return ret
def _is_hidden(self, frame):
if not self.config.enable_hidden_frames:
return False
# Decorated code is always considered to be hidden.
consts = frame.f_code.co_consts
if consts and consts[-1] is _HIDE_FRAME:
return True
# Do not hide if this frame contains the initial set_trace.
if frame is getattr(self, "_via_set_trace_frame", None):
return False
if frame.f_globals.get('__unittest'):
return True
if frame.f_locals.get('__tracebackhide__') \
or frame.f_globals.get('__tracebackhide__'):
return True
def get_stack(self, f, t):
# show all the frames, except the ones that explicitly ask to be hidden
fullstack, idx = super(Pdb, self).get_stack(f, t)
self.fullstack = fullstack
return self.compute_stack(fullstack, idx)
def compute_stack(self, fullstack, idx=None):
if idx is None:
idx = len(fullstack) - 1
if self.show_hidden_frames:
return fullstack, idx
self.hidden_frames = []
newstack = []
for frame, lineno in fullstack:
if self._is_hidden(frame):
self.hidden_frames.append((frame, lineno))
else:
newstack.append((frame, lineno))
newidx = idx - len(self.hidden_frames)
return newstack, newidx
def refresh_stack(self):
"""
Recompute the stack after e.g. show_hidden_frames has been modified
"""
self.stack, _ = self.compute_stack(self.fullstack)
# find the current frame in the new stack
for i, (frame, _) in enumerate(self.stack):
if frame is self.curframe:
self.curindex = i
break
else:
self.curindex = len(self.stack)-1
self.curframe = self.stack[-1][0]
self.print_current_stack_entry()
def forget(self):
if not getattr(local, "_pdbpp_completing", False):
super(Pdb, self).forget()
@classmethod
def _get_all_completions(cls, complete, text):
r = []
i = 0
while True:
comp = complete(text, i)
if comp is None:
break
i += 1
r.append(comp)
return r
@contextlib.contextmanager
def _patch_readline_for_pyrepl(self):
"""Patch readline module used in original Pdb.complete."""
uses_pyrepl = self.fancycompleter.config.readline != sys.modules["readline"]
if not uses_pyrepl:
yield
return
# Make pdb.Pdb.complete use pyrepl's readline.
orig_readline = sys.modules["readline"]
sys.modules["readline"] = self.fancycompleter.config.readline
try:
yield
finally:
sys.modules["readline"] = orig_readline
def complete(self, text, state):
"""Handle completions from fancycompleter and original pdb."""
if state == 0:
local._pdbpp_completing = True
self._completions = []
# Get completions from original pdb.
with self._patch_readline_for_pyrepl():
real_pdb = super(Pdb, self)
for x in self._get_all_completions(real_pdb.complete, text):
if x not in self._completions:
self._completions.append(x)
# Get completions from fancycompleter.
mydict = self.curframe.f_globals.copy()
mydict.update(self.curframe_locals)
completer = Completer(mydict)
completions = self._get_all_completions(completer.complete, text)
# Ignore "\t" as only completion from fancycompleter, if there are
# pdb completions, and remove duplicate completions.
if completions and (completions != ["\t"] or not len(self._completions)):
RE_REMOVE_ESCAPE_SEQS = re.compile(r"\x1b\[[\d;]+m")
clean_fancy_completions = set([
RE_REMOVE_ESCAPE_SEQS.sub("", x) for x in completions
])
self._completions = [
x for x in self._completions
if x not in clean_fancy_completions
]
self._completions.extend(completions)
self._filter_completions(text)
local._pdbpp_completing = False
try:
return self._completions[state]
except IndexError:
return None
def _filter_completions(self, text):
# Remove anything prefixed with "_" / "__" by default, but only
# display it on additional request (3rd tab, after pyrepl's "[not
# unique]"), or if the prefix is used already.
if text == self._lastcompstate[0]:
if self._lastcompstate[1] > 0:
return
self._lastcompstate[1] += 1
else:
self._lastcompstate[0] = text
self._lastcompstate[1] = 0
if text[-1:] != "_":
self._completions = [
x
for x in self._completions
if RE_COLOR_ESCAPES.sub("", x)[:1] != "_"
]
elif text[-2:] != "__":
self._completions = [
x
for x in self._completions
if RE_COLOR_ESCAPES.sub("", x)[:2] != "__"
]
def _init_pygments(self):
if not self.config.use_pygments:
return False
if hasattr(self, '_fmt'):
return True
try:
from pygments.lexers import PythonLexer
from pygments.formatters import TerminalFormatter, Terminal256Formatter
except ImportError:
return False
if hasattr(self.config, 'formatter'):
self._fmt = self.config.formatter
else:
if (self.config.use_terminal256formatter
or (self.config.use_terminal256formatter is None
and "256color" in os.environ.get("TERM", ""))):
Formatter = Terminal256Formatter
else:
Formatter = TerminalFormatter
self._fmt = Formatter(bg=self.config.bg,
colorscheme=self.config.colorscheme)
self._lexer = PythonLexer(stripnl=False)
return True
stack_entry_regexp = re.compile(r'(.*?)\(([0-9]+?)\)(.*)', re.DOTALL)
def format_stack_entry(self, frame_lineno, lprefix=': '):
entry = super(Pdb, self).format_stack_entry(frame_lineno, lprefix)
entry = self.try_to_decode(entry)
if self.config.highlight:
match = self.stack_entry_regexp.match(entry)
if match:
filename, lineno, other = match.groups()
filename = Color.set(self.config.filename_color, filename)
lineno = Color.set(self.config.line_number_color, lineno)
entry = '%s(%s)%s' % (filename, lineno, other)
if self.config.use_pygments:
loc, _, source = entry.rpartition(lprefix)
if _:
entry = loc + _ + self.format_source(source).rstrip()
return entry
def try_to_decode(self, s):
for encoding in self.config.encodings:
try:
return s.decode(encoding)
except (UnicodeDecodeError, AttributeError):
pass
return s
def format_source(self, src):
if not self._init_pygments():
return src
from pygments import highlight
src = self.try_to_decode(src)
return highlight(src, self._lexer, self._fmt)
def _format_line(self, lineno, marker, line, lineno_width):
lineno = ('%%%dd' % lineno_width) % lineno
if self.config.highlight:
lineno = Color.set(self.config.line_number_color, lineno)
line = '%s %2s %s' % (lineno, marker, line)
if self.config.highlight and marker == '->':
if self.config.current_line_color:
line = setbgcolor(line, self.config.current_line_color)
return line
def execRcLines(self):
self._pdbpp_executing_rc_lines = True
try:
return super(Pdb, self).execRcLines()
finally:
del self._pdbpp_executing_rc_lines
def parseline(self, line):
if getattr(self, "_pdbpp_executing_rc_lines", False):
return super(Pdb, self).parseline(line)
if line.startswith('!!'):
# Force the "standard" behaviour, i.e. first check for the
# command, then for the variable name to display.
line = line[2:]
return super(Pdb, self).parseline(line)
if line.endswith('?') and not line.startswith("!"):
arg = line.split('?', 1)[0]
if line.endswith('??'):
cmd = 'source'
self.do_inspect(arg)
self.stdout.write('%-28s\n' % Color.set(Color.red, 'Source:'))
elif (hasattr(self, 'do_' + arg)
and arg not in self.curframe.f_globals
and arg not in self.curframe_locals):
cmd = "help"
else:
cmd = "inspect"
return cmd, arg, line
# pdb++ "smart command mode": don't execute commands if a variable
# with the name exists in the current context;
# This prevents pdb to quit if you type e.g. 'r[0]' by mystake.
cmd, arg, newline = super(Pdb, self).parseline(line)
if cmd:
# prefixed strings.
if (
cmd in ("b", "f", "r", "u")
and len(newline) > 1
and (newline[1] == "'" or newline[1] == '"')
):
cmd, arg, newline = None, None, line
elif hasattr(self, "do_" + cmd):
if (
self.curframe
and (cmd in self.curframe.f_globals or cmd in self.curframe_locals)
) or arg.startswith("="):
cmd, arg, newline = None, None, line
elif cmd == "list" and arg.startswith("("):
# heuristic: handle "list(..." as the builtin.
cmd, arg, newline = None, None, line
# Fix cmd to not be None when used in completions.
# This would trigger a TypeError (instead of AttributeError) in
# Cmd.complete (https://bugs.python.org/issue35270).
if cmd is None:
f = sys._getframe()
while f.f_back:
f = f.f_back
if f.f_code.co_name == "complete":
cmd = ""
break
return cmd, arg, newline
def do_inspect(self, arg):
obj = self._getval(arg)
data = OrderedDict()
data['Type'] = type(obj).__name__
data['String Form'] = str(obj).strip()
try:
data['Length'] = len(obj)
except TypeError:
pass
try:
data['File'] = inspect.getabsfile(obj)
except TypeError:
pass
if (isinstance(obj, type)
and hasattr(obj, '__init__')
and getattr(obj, '__module__') != '__builtin__'):
# Class - show definition and docstring for constructor
data['Docstring'] = obj.__doc__
data['Constructor information'] = ''
try:
data[' Definition'] = '%s%s' % (arg, signature(obj))
except ValueError:
pass
data[' Docstring'] = obj.__init__.__doc__
else:
try:
data['Definition'] = '%s%s' % (arg, signature(obj))
except (TypeError, ValueError):
pass
data['Docstring'] = obj.__doc__
for key, value in data.items():
formatted_key = Color.set(Color.red, key + ':')
self.stdout.write('%-28s %s\n' % (formatted_key, value))
def default(self, line):
"""Patched version to fix namespace with list comprehensions.
Fixes https://bugs.python.org/issue21161.
"""
self.history.append(line)
if line[:1] == '!':
line = line[1:]
locals = self.curframe_locals
ns = self.curframe.f_globals.copy()
ns.update(locals)
try:
code = compile(line + '\n', '<stdin>', 'single')
save_stdout = sys.stdout
save_stdin = sys.stdin
save_displayhook = sys.displayhook
try:
sys.stdin = self.stdin
sys.stdout = self.stdout
sys.displayhook = self.displayhook
exec(code, ns, locals)
finally:
sys.stdout = save_stdout
sys.stdin = save_stdin
sys.displayhook = save_displayhook
except:
exc_info = sys.exc_info()[:2]
self.error(traceback.format_exception_only(*exc_info)[-1].strip())
def do_help(self, arg):
try:
return super(Pdb, self).do_help(arg)
except AttributeError:
print("*** No help for '{command}'".format(command=arg),
file=self.stdout)
do_help.__doc__ = pdb.Pdb.do_help.__doc__
def help_hidden_frames(self):
print("""\
Some frames might be marked as "hidden": by default, hidden frames are not
shown in the stack trace, and cannot be reached using ``up`` and ``down``.
You can use ``hf_unhide`` to tell pdb++ to ignore the hidden status (i.e., to
treat hidden frames as normal ones), and ``hf_hide`` to hide them again.
``hf_list`` prints a list of hidden frames.
Frames can be marked as hidden in the following ways:
- by using the ``@pdb.hideframe`` function decorator
- by having ``__tracebackhide__=True`` in the locals or the globals of the
function (this is used by pytest)
- by having ``__unittest=True`` in the globals of the function (this hides
unittest internal stuff)
- by providing a list of skip patterns to the Pdb class constructor. This
list defaults to ``skip=["importlib._bootstrap"]``.
Note that the initial frame where ``set_trace`` was called from is not hidden,
except for when using the function decorator.
""", file=self.stdout)
def do_hf_unhide(self, arg):
"""
{hf_show}
unhide hidden frames, i.e. make it possible to ``up`` or ``down``
there
"""
self.show_hidden_frames = True
self.refresh_stack()
def do_hf_hide(self, arg):
"""
{hf_hide}
(re)hide hidden frames, if they have been unhidden by ``hf_unhide``
"""
self.show_hidden_frames = False
self.refresh_stack()
def do_hf_list(self, arg):
for frame_lineno in self.hidden_frames:
print(self.format_stack_entry(frame_lineno, pdb.line_prefix),
file=self.stdout)
def do_longlist(self, arg):
"""
{longlist|ll}
List source code for the current function.
Differently than list, the whole function is displayed; the
current line is marked with '->'. In case of post-mortem
debugging, the line which effectively raised the exception is
marked with '>>'.
If the 'highlight' config option is set and pygments is
installed, the source code is colorized.
"""
self.lastcmd = 'longlist'
self._printlonglist()
do_ll = do_longlist
def _printlonglist(self, linerange=None):
try:
if self.curframe.f_code.co_name == '<module>':
# inspect.getsourcelines is buggy in this case: if we just
# pass the frame, it returns the source for the first function
# defined in the module. Instead, we want the full source
# code of the module
lines, _ = inspect.findsource(self.curframe)
lineno = 1
else:
try:
lines, lineno = inspect.getsourcelines(self.curframe)
except Exception as e:
print('** Error in inspect.getsourcelines: %s **' %
e, file=self.stdout)
return
except IOError as e:
print('** Error: %s **' % e, file=self.stdout)
return
if linerange:
start, end = linerange
start = max(start, lineno)
end = min(end, lineno+len(lines))
lines = lines[start-lineno:end-lineno]
lineno = start
self._print_lines_pdbpp(lines, lineno)
def _print_lines_pdbpp(self, lines, lineno, print_markers=True):
lines = [line[:-1] for line in lines] # remove the trailing '\n'
lines = [line.replace('\t', ' ')
for line in lines] # force tabs to 4 spaces
width, height = self.get_terminal_size()
if self.config.truncate_long_lines:
maxlength = max(width - 9, 16)
lines = [line[:maxlength] for line in lines]
else:
maxlength = max(map(len, lines))
if print_markers:
exc_lineno = self.tb_lineno.get(self.curframe, None)
if height >= 6:
last_marker_line = max(
self.curframe.f_lineno,
exc_lineno if exc_lineno else 0) - lineno
if last_marker_line >= 0:
maxlines = last_marker_line + height * 2 // 3
if len(lines) > maxlines:
lines = lines[:maxlines]
lines.append('...')
if self.config.highlight and print_markers:
# Fill with spaces. This is important for setbgcolor, although
# only for the current/marked line really.
lines = [line.ljust(maxlength) for line in lines]
if self.config.use_pygments:
src = self.format_source('\n'.join(lines))
lines = src.splitlines()
lineno_width = len(str(lineno + len(lines)))
if print_markers:
for i, line in enumerate(lines):
if lineno == self.curframe.f_lineno:
marker = '->'
elif lineno == exc_lineno:
marker = '>>'
else:
marker = ''
lines[i] = self._format_line(lineno, marker, line, lineno_width)
lineno += 1
else:
for i, line in enumerate(lines):
lines[i] = self._format_line(lineno, '', line, lineno_width)
lineno += 1
print('\n'.join(lines), file=self.stdout)
def _format_source_lines(self, lines):
if not lines:
return lines
if not self.config.use_pygments and not self.config.highlight:
return lines
# Format source without prefixes added by pdb, including line numbers.
prefixes = []
src_lines = []
for x in lines:
prefix, _, src = x.partition('\t')
prefixes.append(prefix)
src_lines.append(src)
formatted_src_lines = self.format_source(
"\n".join(src_lines) + "\n"
).splitlines()
RE_LNUM_PREFIX = re.compile(r"^\d+")
if self.config.highlight:
prefixes = [
RE_LNUM_PREFIX.sub(
lambda m: Color.set(self.config.line_number_color, m.group(0)),
prefix
)
for prefix in prefixes
]
return [
"%s\t%s" % (prefix, src)
for (prefix, src) in zip(prefixes, formatted_src_lines)
]
if sys.version_info >= (3, 2):
def _print_lines(self, lines, *args, **kwargs):
"""Enhance original _print_lines with highlighting.
Used via do_list currently only, do_source and do_longlist are
overridden.
"""
if not lines or not (self.config.use_pygments or self.config.highlight):
return super(Pdb, self)._print_lines(lines, *args, **kwargs)
oldstdout = self.stdout
self.stdout = StringIO()
ret = super(Pdb, self)._print_lines(lines, *args, **kwargs)
orig_pdb_lines = self.stdout.getvalue().splitlines()
self.stdout = oldstdout
for line in self._format_source_lines(orig_pdb_lines):
print(line, file=self.stdout)
return ret
else:
# Only for Python 2.7, where _print_lines is not used/available.
def do_list(self, arg):
if not (self.config.use_pygments or self.config.highlight):
return super(Pdb, self).do_list(arg)
oldstdout = self.stdout
self.stdout = StringIO()
ret = super(Pdb, self).do_list(arg)
orig_pdb_lines = self.stdout.getvalue().splitlines()
self.stdout = oldstdout
for line in self._format_source_lines(orig_pdb_lines):
print(line, file=self.stdout)
return ret
do_list.__doc__ = pdb.Pdb.do_list.__doc__
do_l = do_list
def do_continue(self, arg):
if arg != '':
self.do_tbreak(arg)
return super(Pdb, self).do_continue('')
do_continue.__doc__ = pdb.Pdb.do_continue.__doc__
do_c = do_cont = do_continue
def do_p(self, arg):
"""p expression
Print the value of the expression.
"""
try:
val = self._getval(arg)
except:
return
try:
self.message(repr(val))
except:
exc_info = sys.exc_info()[:2]
self.error(traceback.format_exception_only(*exc_info)[-1].strip())
def do_pp(self, arg):
try:
val = self._getval(arg)
except:
pass
try:
width, height = self.get_terminal_size()
pprint.pprint(val, self.stdout, width=width)
except:
exc_info = sys.exc_info()[:2]
self.error(traceback.format_exception_only(*exc_info)[-1].strip())
do_pp.__doc__ = pdb.Pdb.do_pp.__doc__
def do_debug(self, arg):
# this is a hack (as usual :-))
#
# inside the original do_debug, there is a call to the global "Pdb" to
# instantiate the recursive debugger: we want to intercept this call
# and instantiate *our* Pdb, passing our custom config. Therefore we
# dynamically rebind the globals.
Config = self.ConfigFactory
class PdbppWithConfig(self.__class__):
def __init__(self_withcfg, *args, **kwargs):
kwargs.setdefault("Config", Config)
super(PdbppWithConfig, self_withcfg).__init__(*args, **kwargs)
# Backport of fix for bpo-31078 (not yet merged).
self_withcfg.use_rawinput = self.use_rawinput
local.GLOBAL_PDB = self_withcfg
if sys.version_info < (3, ):