FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[Original HTTPS Page]
cpython/Lib/pdb.py at 3.15 · python/cpython · GitHub
cpython/Lib/pdb.py at 3.15 · python/cpython · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
python
cpython
Repository navigation
Code
Issues
5k+
(5k+)
Pull requests
2.7k
(2.7k)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Lib
/
pdb.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
3899 lines (3397 loc) · 139 KB
Breadcrumbs
cpython
/
Lib
/
pdb.py
Copy path
File metadata and controls
3899 lines (3397 loc) · 139 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
The Python Debugger Pdb
=======================
To use the debugger in its simplest form:
>>> import pdb
>>> pdb.run('<a statement>')
The debugger's prompt is '(Pdb) '. This will stop in the first
function call in <a statement>.
Alternatively, if a statement terminated with an unhandled exception,
you can use pdb's post-mortem facility to inspect the contents of the
traceback:
>>> <a statement>
<exception traceback>
>>> import pdb
>>> pdb.pm()
The commands recognized by the debugger are listed in the next
section. Most can be abbreviated as indicated; e.g., h(elp) means
that 'help' can be typed as 'h' or 'help' (but not as 'he' or 'hel',
nor as 'H' or 'Help' or 'HELP'). Optional arguments are enclosed in
square brackets. Alternatives in the command syntax are separated
by a vertical bar (|).
A blank line repeats the previous command literally, except for
'list', where it lists the next 11 lines.
Commands that the debugger doesn't recognize are assumed to be Python
statements and are executed in the context of the program being
debugged. Python statements can also be prefixed with an exclamation
point ('!'). This is a powerful way to inspect the program being
debugged; it is even possible to change variables or call functions.
When an exception occurs in such a statement, the exception name is
printed but the debugger's state is not changed.
The debugger supports aliases, which can save typing. And aliases can
have parameters (see the alias help entry) which allows one a certain
level of adaptability to the context under examination.
Multiple commands may be entered on a single line, separated by the
pair ';;'. No intelligence is applied to separating the commands; the
input is split at the first ';;', even if it is in the middle of a
quoted string.
If a file ".pdbrc" exists in your home directory or in the current
directory, it is read in and executed as if it had been typed at the
debugger prompt. This is particularly useful for aliases. If both
files exist, the one in the home directory is read first and aliases
defined there can be overridden by the local file. This behavior can be
disabled by passing the "readrc=False" argument to the Pdb constructor.
Aside from aliases, the debugger is not directly programmable; but it
is implemented as a class from which you can derive your own debugger
class, which you can make as fancy as you like.
Debugger commands
=================
"""
# NOTE: the actual command documentation is collected from docstrings of the
# commands and is appended to __doc__ after the class has been defined.
import
os
import
io
import
re
import
sys
import
cmd
import
bdb
import
dis
import
code
import
glob
import
json
import
stat
import
token
import
types
import
atexit
import
codeop
import
pprint
import
signal
import
socket
import
typing
import
asyncio
import
inspect
import
weakref
import
builtins
import
tempfile
import
textwrap
import
tokenize
import
itertools
import
traceback
import
linecache
import
selectors
import
threading
import
_colorize
from
contextlib
import
ExitStack
,
closing
,
contextmanager
from
types
import
CodeType
from
warnings
import
deprecated
try
:
import
_pyrepl
.
utils
except
ModuleNotFoundError
:
_pyrepl
=
None
class
Restart
(
Exception
):
"""Causes a debugger to be restarted for the debugged python program."""
pass
__all__
=
[
"run"
,
"pm"
,
"Pdb"
,
"runeval"
,
"runctx"
,
"runcall"
,
"set_trace"
,
"post_mortem"
,
"set_default_backend"
,
"get_default_backend"
,
"help"
]
def
find_first_executable_line
(
code
):
""" Try to find the first executable line of the code object.
Equivalently, find the line number of the instruction that's
after RESUME
Return code.co_firstlineno if no executable line is found.
"""
prev
=
None
for
instr
in
dis
.
get_instructions
(
code
):
if
prev
is
not
None
and
prev
.
opname
==
'RESUME'
:
if
instr
.
positions
.
lineno
is
not
None
:
return
instr
.
positions
.
lineno
return
code
.
co_firstlineno
prev
=
instr
return
code
.
co_firstlineno
def
find_function
(
funcname
,
filename
):
cre
=
re
.
compile
(
r'(?:async\s+)?def\s+%s(\s*\[.+\])?\s*[(]'
%
re
.
escape
(
funcname
))
try
:
fp
=
tokenize
.
open
(
filename
)
except
OSError
:
lines
=
linecache
.
getlines
(
filename
)
if
not
lines
:
return
None
fp
=
io
.
StringIO
(
''
.
join
(
lines
))
funcdef
=
""
funcstart
=
0
# consumer of this info expects the first line to be 1
with
fp
:
for
lineno
,
line
in
enumerate
(
fp
,
start
=
1
):
if
cre
.
match
(
line
):
funcstart
,
funcdef
=
lineno
,
line
elif
funcdef
:
funcdef
+=
line
if
funcdef
:
try
:
code
=
compile
(
funcdef
,
filename
,
'exec'
)
except
Exception
:
continue
# We should always be able to find the code object here
funccode
=
next
(
c
for
c
in
code
.
co_consts
if
isinstance
(
c
,
CodeType
)
and
c
.
co_name
==
funcname
)
lineno_offset
=
find_first_executable_line
(
funccode
)
return
funcname
,
filename
,
funcstart
+
lineno_offset
-
1
return
None
def
lasti2lineno
(
code
,
lasti
):
linestarts
=
list
(
dis
.
findlinestarts
(
code
))
linestarts
.
reverse
()
for
i
,
lineno
in
linestarts
:
if
lasti
>=
i
:
return
lineno
return
0
class
_rstr
(
str
):
"""String that doesn't quote its repr."""
def
__repr__
(
self
):
return
self
class
_ExecutableTarget
:
filename
:
str
code
:
CodeType
|
str
namespace
:
dict
class
_ScriptTarget
(
_ExecutableTarget
):
def
__init__
(
self
,
target
):
self
.
_check
(
target
)
self
.
_target
=
self
.
_safe_realpath
(
target
)
# If PYTHONSAFEPATH (-P) is not set, sys.path[0] is the directory
# of pdb, and we should replace it with the directory of the script
if
not
sys
.
flags
.
safe_path
:
sys
.
path
[
0
]
=
os
.
path
.
dirname
(
self
.
_target
)
@
staticmethod
def
_check
(
target
):
"""
Check that target is plausibly a script.
"""
if
not
os
.
path
.
exists
(
target
):
print
(
f'Error:
{
target
}
does not exist'
)
sys
.
exit
(
1
)
if
os
.
path
.
isdir
(
target
):
print
(
f'Error:
{
target
}
is a directory'
)
sys
.
exit
(
1
)
@
staticmethod
def
_safe_realpath
(
path
):
"""
Return the canonical path (realpath) if it is accessible from the userspace.
Otherwise (for example, if the path is a symlink to an anonymous pipe),
return the original path.
See GH-142315.
"""
realpath
=
os
.
path
.
realpath
(
path
)
return
realpath
if
os
.
path
.
exists
(
realpath
)
else
path
def
__repr__
(
self
):
return
self
.
_target
@
property
def
filename
(
self
):
return
self
.
_target
@
property
def
code
(
self
):
# Open the file each time because the file may be modified
with
io
.
open_code
(
self
.
_target
)
as
fp
:
return
f"exec(compile(
{
fp
.
read
()!r
}
,
{
self
.
_target
!r
}
, 'exec'))"
@
property
def
namespace
(
self
):
return
dict
(
__name__
=
'__main__'
,
__file__
=
self
.
_target
,
__builtins__
=
__builtins__
,
__spec__
=
None
,
)
class
_ModuleTarget
(
_ExecutableTarget
):
def
__init__
(
self
,
target
):
self
.
_target
=
target
import
runpy
try
:
_
,
self
.
_spec
,
self
.
_code
=
runpy
.
_get_module_details
(
self
.
_target
)
except
ImportError
as
e
:
print
(
f"ImportError:
{
e
}
"
)
sys
.
exit
(
1
)
except
Exception
:
traceback
.
print_exc
()
sys
.
exit
(
1
)
def
__repr__
(
self
):
return
self
.
_target
@
property
def
filename
(
self
):
return
self
.
_code
.
co_filename
@
property
def
code
(
self
):
return
self
.
_code
@
property
def
namespace
(
self
):
return
dict
(
__name__
=
'__main__'
,
__file__
=
os
.
path
.
normcase
(
os
.
path
.
abspath
(
self
.
filename
)),
__package__
=
self
.
_spec
.
parent
,
__loader__
=
self
.
_spec
.
loader
,
__spec__
=
self
.
_spec
,
__builtins__
=
__builtins__
,
)
class
_ZipTarget
(
_ExecutableTarget
):
def
__init__
(
self
,
target
):
import
runpy
self
.
_target
=
os
.
path
.
realpath
(
target
)
sys
.
path
.
insert
(
0
,
self
.
_target
)
try
:
_
,
self
.
_spec
,
self
.
_code
=
runpy
.
_get_main_module_details
()
except
ImportError
as
e
:
print
(
f"ImportError:
{
e
}
"
)
sys
.
exit
(
1
)
except
Exception
:
traceback
.
print_exc
()
sys
.
exit
(
1
)
def
__repr__
(
self
):
return
self
.
_target
@
property
def
filename
(
self
):
return
self
.
_code
.
co_filename
@
property
def
code
(
self
):
return
self
.
_code
@
property
def
namespace
(
self
):
return
dict
(
__name__
=
'__main__'
,
__file__
=
os
.
path
.
normcase
(
os
.
path
.
abspath
(
self
.
filename
)),
__package__
=
self
.
_spec
.
parent
,
__loader__
=
self
.
_spec
.
loader
,
__spec__
=
self
.
_spec
,
__builtins__
=
__builtins__
,
)
class
_PdbInteractiveConsole
(
code
.
InteractiveConsole
):
def
__init__
(
self
,
ns
=
None
,
message
=
None
):
self
.
_message
=
message
super
().
__init__
(
locals
=
ns
,
local_exit
=
True
)
def
write
(
self
,
data
):
if
self
.
_message
is
not
None
:
self
.
_message
(
data
,
end
=
''
)
else
:
super
().
write
(
data
)
def
more_lines
(
self
,
text
):
# Generic Python multi-line completeness heuristic.
# Strips pyrepl's trailing auto-indent before compiling.
# This should be functionally identical to simple_interact._more_lines
src
=
text
.
rstrip
(
"
\t
"
)
n
=
len
(
src
)
if
n
>
0
and
text
[
n
-
1
]
==
'
\n
'
:
text
=
src
try
:
code_obj
=
self
.
compile
(
text
,
"<stdin>"
,
"single"
)
except
(
OverflowError
,
SyntaxError
,
ValueError
):
lines
=
text
.
splitlines
(
keepends
=
True
)
if
len
(
lines
)
==
1
:
return
False
last
=
lines
[
-
1
]
return
((
last
.
startswith
((
" "
,
"
\t
"
))
or
last
.
strip
()
!=
""
)
and
not
last
.
endswith
(
"
\n
"
))
return
code_obj
is
None
# Interaction prompt line will separate file and call info from code
# text using value of line_prefix string. A newline and arrow may
# be to your liking. You can set it once pdb is imported using the
# command "pdb.line_prefix = '\n% '".
# line_prefix = ': ' # Use this to get the old situation back
line_prefix
=
'
\n
-> '
# Probably a better default
# The default backend to use for Pdb instances if not specified
# Should be either 'settrace' or 'monitoring'
_default_backend
=
'settrace'
def
set_default_backend
(
backend
):
"""Set the default backend to use for Pdb instances."""
global
_default_backend
if
backend
not
in
(
'settrace'
,
'monitoring'
):
raise
ValueError
(
"Invalid backend: %s"
%
backend
)
_default_backend
=
backend
def
get_default_backend
():
"""Get the default backend to use for Pdb instances."""
return
_default_backend
def
_pyrepl_available
():
"""return whether pdb should use _pyrepl for input"""
if
os
.
getenv
(
"PYTHON_BASIC_REPL"
):
CAN_USE_PYREPL
=
False
else
:
try
:
from
_pyrepl
.
main
import
CAN_USE_PYREPL
except
ModuleNotFoundError
:
CAN_USE_PYREPL
=
False
return
CAN_USE_PYREPL
class
PdbPyReplInput
:
def
__init__
(
self
,
pdb_instance
,
stdin
,
stdout
,
prompt
):
import
_pyrepl
.
readline
self
.
pdb_instance
=
pdb_instance
self
.
prompt
=
prompt
self
.
console
=
_PdbInteractiveConsole
()
if
not
(
os
.
isatty
(
stdin
.
fileno
())):
raise
ValueError
(
"stdin is not a TTY"
)
self
.
readline_wrapper
=
_pyrepl
.
readline
.
_ReadlineWrapper
(
f_in
=
stdin
.
fileno
(),
f_out
=
stdout
.
fileno
(),
config
=
_pyrepl
.
readline
.
ReadlineConfig
(
completer_delims
=
frozenset
(
'
\t
\n
`@#%^&*()=+[{]}
\\
|;:
\'
",<>?'
)
)
)
self
.
readline_wrapper
.
get_reader
().
gen_colors
=
self
.
gen_colors
def
readline
(
self
):
def
more_lines
(
text
):
if
text
.
strip
()
==
"
\x1a
"
:
# Ctrl + Z raises EOFError to quit pdb
# This is similarly handled in simple_interact.py
raise
EOFError
cmd
,
_
,
line
=
self
.
pdb_instance
.
parseline
(
text
)
if
not
line
or
not
cmd
:
return
False
func
=
getattr
(
self
.
pdb_instance
,
'do_'
+
cmd
,
None
)
if
func
is
not
None
:
return
False
return
self
.
console
.
more_lines
(
text
)
try
:
pyrepl_completer
=
self
.
readline_wrapper
.
get_completer
()
self
.
readline_wrapper
.
set_completer
(
self
.
complete
)
multiline
=
(
self
.
readline_wrapper
.
multiline_input
(
more_lines
,
self
.
prompt
,
'... '
+
' '
*
(
len
(
self
.
prompt
)
-
4
)
)
+
'
\n
'
)
return
multiline
except
EOFError
:
return
'EOF'
finally
:
self
.
readline_wrapper
.
set_completer
(
pyrepl_completer
)
def
complete
(
self
,
text
,
state
):
"""
This function is very similar to cmd.Cmd.complete.
However, cmd.Cmd.complete assumes that we use readline module, but
pyrepl does not use it.
"""
if
state
==
0
:
origline
=
self
.
readline_wrapper
.
get_line_buffer
()
line
=
origline
.
lstrip
()
stripped
=
len
(
origline
)
-
len
(
line
)
begidx
=
self
.
readline_wrapper
.
get_begidx
()
-
stripped
endidx
=
self
.
readline_wrapper
.
get_endidx
()
-
stripped
if
begidx
>
0
:
cmd
,
args
,
foo
=
self
.
pdb_instance
.
parseline
(
line
)
if
not
cmd
:
compfunc
=
self
.
pdb_instance
.
completedefault
else
:
try
:
compfunc
=
getattr
(
self
.
pdb_instance
,
'complete_'
+
cmd
)
except
AttributeError
:
compfunc
=
self
.
pdb_instance
.
completedefault
else
:
compfunc
=
self
.
pdb_instance
.
completenames
self
.
completion_matches
=
compfunc
(
text
,
line
,
begidx
,
endidx
)
try
:
return
self
.
completion_matches
[
state
]
except
IndexError
:
return
None
def
gen_colors
(
self
,
buffer
):
from
_pyrepl
.
utils
import
ColorSpan
,
Span
if
not
buffer
.
strip
():
return
leading_spaces
=
len
(
buffer
)
-
len
(
buffer
.
lstrip
())
leading_text
=
buffer
.
split
()[
0
]
if
hasattr
(
self
.
pdb_instance
,
'do_'
+
leading_text
):
yield
ColorSpan
(
Span
(
leading_spaces
,
leading_spaces
+
len
(
leading_text
)
-
1
),
"soft_keyword"
)
# Redact the command text with spaces so there will be no duplicated
# color span generated for it later.
redact_length
=
leading_spaces
+
len
(
leading_text
)
buffer
=
' '
*
redact_length
+
buffer
[
redact_length
:]
yield
from
_pyrepl
.
utils
.
gen_colors
(
buffer
)
class
Pdb
(
bdb
.
Bdb
,
cmd
.
Cmd
):
_previous_sigint_handler
=
None
# Limit the maximum depth of chained exceptions, we should be handling cycles,
# but in case there are recursions, we stop at 999.
MAX_CHAINED_EXCEPTION_DEPTH
=
999
_file_mtime_table
=
{}
_last_pdb_instance
=
None
def
__init__
(
self
,
completekey
=
'tab'
,
stdin
=
None
,
stdout
=
None
,
skip
=
None
,
nosigint
=
False
,
readrc
=
True
,
mode
=
None
,
backend
=
None
,
colorize
=
False
):
bdb
.
Bdb
.
__init__
(
self
,
skip
=
skip
,
backend
=
backend
if
backend
else
get_default_backend
())
cmd
.
Cmd
.
__init__
(
self
,
completekey
,
stdin
,
stdout
)
sys
.
audit
(
"pdb.Pdb"
)
if
stdin
is
not
None
and
stdin
is
not
sys
.
stdin
:
self
.
use_rawinput
=
False
self
.
prompt
=
'(Pdb) '
self
.
aliases
=
{}
self
.
displaying
=
{}
self
.
mainpyfile
=
''
self
.
_wait_for_mainpyfile
=
False
self
.
tb_lineno
=
{}
self
.
mode
=
mode
self
.
colorize
=
colorize
and
_colorize
.
can_colorize
(
file
=
stdout
or
sys
.
stdout
)
# Try to load readline if it exists
try
:
import
readline
# remove some common file name delimiters
readline
.
set_completer_delims
(
'
\t
\n
`@#%^&*()=+[{]}
\\
|;:
\'
",<>?'
)
except
ImportError
:
pass
self
.
pyrepl_input
=
None
if
_pyrepl_available
():
try
:
self
.
pyrepl_input
=
PdbPyReplInput
(
self
,
self
.
stdin
,
self
.
stdout
,
self
.
prompt
)
except
Exception
:
pass
self
.
allow_kbdint
=
False
self
.
nosigint
=
nosigint
# Consider these characters as part of the command so when the users type
# c.a or c['a'], it won't be recognized as a c(ontinue) command
self
.
identchars
=
cmd
.
Cmd
.
identchars
+
'=.[](),"
\'
+-*/%@&|<>~^'
# Read ~/.pdbrc and ./.pdbrc
self
.
rcLines
=
[]
if
readrc
:
home_rcfile
=
os
.
path
.
expanduser
(
"~/.pdbrc"
)
local_rcfile
=
os
.
path
.
abspath
(
".pdbrc"
)
try
:
with
open
(
home_rcfile
,
encoding
=
'utf-8'
)
as
rcfile
:
self
.
rcLines
.
extend
(
rcfile
)
except
OSError
:
pass
if
local_rcfile
!=
home_rcfile
:
try
:
with
open
(
local_rcfile
,
encoding
=
'utf-8'
)
as
rcfile
:
self
.
rcLines
.
extend
(
rcfile
)
except
OSError
:
pass
self
.
commands
=
{}
# associates a command list to breakpoint numbers
self
.
commands_defining
=
False
# True while in the process of defining
# a command list
self
.
commands_bnum
=
None
# The breakpoint number for which we are
# defining a list
self
.
async_shim_frame
=
None
self
.
async_awaitable
=
None
self
.
_chained_exceptions
=
tuple
()
self
.
_chained_exception_index
=
0
self
.
_current_task
=
None
self
.
lineno
=
None
self
.
stack
=
[]
self
.
curindex
=
0
self
.
curframe
=
None
self
.
_user_requested_quit
=
False
def
set_trace
(
self
,
frame
=
None
,
*
,
commands
=
None
):
Pdb
.
_last_pdb_instance
=
self
if
frame
is
None
:
frame
=
sys
.
_getframe
().
f_back
if
commands
is
not
None
:
self
.
rcLines
.
extend
(
commands
)
super
().
set_trace
(
frame
)
async
def
set_trace_async
(
self
,
frame
=
None
,
*
,
commands
=
None
):
if
self
.
async_awaitable
is
not
None
:
# We are already in a set_trace_async call, do not mess with it
return
if
frame
is
None
:
frame
=
sys
.
_getframe
().
f_back
# We need set_trace to set up the basics, however, this will call
# set_stepinstr() will we need to compensate for, because we don't
# want to trigger on calls
self
.
set_trace
(
frame
,
commands
=
commands
)
# Changing the stopframe will disable trace dispatch on calls
self
.
stopframe
=
frame
# We need to stop tracing because we don't have the privilege to avoid
# triggering tracing functions as normal, as we are not already in
# tracing functions
self
.
stop_trace
()
self
.
async_shim_frame
=
sys
.
_getframe
()
self
.
async_awaitable
=
None
while
True
:
self
.
async_awaitable
=
None
# Simulate a trace event
# This should bring up pdb and make pdb believe it's debugging the
# caller frame
self
.
trace_dispatch
(
frame
,
"opcode"
,
None
)
if
self
.
async_awaitable
is
not
None
:
try
:
if
self
.
breaks
:
with
self
.
set_enterframe
(
frame
):
# set_continue requires enterframe to work
self
.
set_continue
()
self
.
start_trace
()
await
self
.
async_awaitable
except
Exception
:
self
.
_error_exc
()
else
:
break
self
.
async_shim_frame
=
None
# start the trace (the actual command is already set by set_* calls)
if
self
.
returnframe
is
None
and
self
.
stoplineno
==
-
1
and
not
self
.
breaks
:
# This means we did a continue without any breakpoints, we should not
# start the trace
return
self
.
start_trace
()
def
sigint_handler
(
self
,
signum
,
frame
):
if
self
.
allow_kbdint
:
raise
KeyboardInterrupt
self
.
message
(
"
\n
Program interrupted. (Use 'cont' to resume)."
)
self
.
set_step
()
self
.
set_trace
(
frame
)
def
reset
(
self
):
bdb
.
Bdb
.
reset
(
self
)
self
.
forget
()
def
forget
(
self
):
self
.
lineno
=
None
self
.
stack
=
[]
self
.
curindex
=
0
if
self
.
curframe
:
self
.
curframe
.
f_globals
.
pop
(
'__pdb_convenience_variables'
,
None
)
self
.
curframe
=
None
self
.
tb_lineno
.
clear
()
def
setup
(
self
,
f
,
tb
):
self
.
forget
()
self
.
stack
,
self
.
curindex
=
self
.
get_stack
(
f
,
tb
)
while
tb
:
# when setting up post-mortem debugging with a traceback, save all
# the original line numbers to be displayed along the current line
# numbers (which can be different, e.g. due to finally clauses)
lineno
=
lasti2lineno
(
tb
.
tb_frame
.
f_code
,
tb
.
tb_lasti
)
self
.
tb_lineno
[
tb
.
tb_frame
]
=
lineno
tb
=
tb
.
tb_next
self
.
curframe
=
self
.
stack
[
self
.
curindex
][
0
]
self
.
set_convenience_variable
(
self
.
curframe
,
'_frame'
,
self
.
curframe
)
if
self
.
_current_task
:
self
.
set_convenience_variable
(
self
.
curframe
,
'_asynctask'
,
self
.
_current_task
)
self
.
_save_initial_file_mtime
(
self
.
curframe
)
if
self
.
_chained_exceptions
:
self
.
set_convenience_variable
(
self
.
curframe
,
'_exception'
,
self
.
_chained_exceptions
[
self
.
_chained_exception_index
],
)
if
self
.
rcLines
:
self
.
cmdqueue
=
[
line
for
line
in
self
.
rcLines
if
line
.
strip
()
and
not
line
.
strip
().
startswith
(
"#"
)
]
self
.
rcLines
=
[]
@
property
@
deprecated
(
"The frame locals reference is no longer cached. Use 'curframe.f_locals' instead."
)
def
curframe_locals
(
self
):
return
self
.
curframe
.
f_locals
@
curframe_locals
.
setter
@
deprecated
(
"Setting 'curframe_locals' no longer has any effect. Update the contents of 'curframe.f_locals' instead."
)
def
curframe_locals
(
self
,
value
):
pass
# Override Bdb methods
def
user_call
(
self
,
frame
,
argument_list
):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
if
self
.
_wait_for_mainpyfile
:
return
if
self
.
stop_here
(
frame
):
self
.
message
(
'--Call--'
)
self
.
interaction
(
frame
,
None
)
def
user_line
(
self
,
frame
):
"""This function is called when we stop or break at this line."""
if
self
.
_wait_for_mainpyfile
:
if
(
self
.
mainpyfile
!=
self
.
canonic
(
frame
.
f_code
.
co_filename
)):
return
self
.
_wait_for_mainpyfile
=
False
if
self
.
trace_opcodes
:
# GH-127321
# We want to avoid stopping at an opcode that does not have
# an associated line number because pdb does not like it
if
frame
.
f_lineno
is
None
:
self
.
set_stepinstr
()
return
self
.
bp_commands
(
frame
)
self
.
interaction
(
frame
,
None
)
user_opcode
=
user_line
def
bp_commands
(
self
,
frame
):
"""Call every command that was set for the current active breakpoint
(if there is one).
Returns True if the normal interaction function must be called,
False otherwise."""
# self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit
if
getattr
(
self
,
"currentbp"
,
False
)
and
\
self
.
currentbp
in
self
.
commands
:
currentbp
=
self
.
currentbp
self
.
currentbp
=
0
for
line
in
self
.
commands
[
currentbp
]:
self
.
cmdqueue
.
append
(
line
)
self
.
cmdqueue
.
append
(
f'_pdbcmd_restore_lastcmd
{
self
.
lastcmd
}
'
)
def
user_return
(
self
,
frame
,
return_value
):
"""This function is called when a return trap is set here."""
if
self
.
_wait_for_mainpyfile
:
return
frame
.
f_locals
[
'__return__'
]
=
return_value
self
.
set_convenience_variable
(
frame
,
'_retval'
,
return_value
)
self
.
message
(
'--Return--'
)
self
.
interaction
(
frame
,
None
)
def
user_exception
(
self
,
frame
,
exc_info
):
"""This function is called if an exception occurs,
but only if we are to stop at or just below this level."""
if
self
.
_wait_for_mainpyfile
:
return
exc_type
,
exc_value
,
exc_traceback
=
exc_info
frame
.
f_locals
[
'__exception__'
]
=
exc_type
,
exc_value
self
.
set_convenience_variable
(
frame
,
'_exception'
,
exc_value
)
# An 'Internal StopIteration' exception is an exception debug event
# issued by the interpreter when handling a subgenerator run with
# 'yield from' or a generator controlled by a for loop. No exception has
# actually occurred in this case. The debugger uses this debug event to
# stop when the debuggee is returning from such generators.
prefix
=
'Internal '
if
(
not
exc_traceback
and
exc_type
is
StopIteration
)
else
''
self
.
message
(
'%s%s'
%
(
prefix
,
self
.
_format_exc
(
exc_value
)))
self
.
interaction
(
frame
,
exc_traceback
)
@
contextmanager
def
_replace_attribute
(
self
,
attrs
):
original_attrs
=
{}
for
attr
,
value
in
attrs
.
items
():
original_attrs
[
attr
]
=
getattr
(
self
,
attr
)
setattr
(
self
,
attr
,
value
)
try
:
yield
finally
:
for
attr
,
value
in
original_attrs
.
items
():
setattr
(
self
,
attr
,
value
)
@
contextmanager
def
_maybe_use_pyrepl_as_stdin
(
self
):
if
self
.
pyrepl_input
is
None
:
yield
return
with
self
.
_replace_attribute
({
'stdin'
:
self
.
pyrepl_input
,
'use_rawinput'
:
False
,
'prompt'
:
''
,
}):
yield
# General interaction function
def
_cmdloop
(
self
):
while
True
:
try
:
# keyboard interrupts allow for an easy way to cancel
# the current command, so allow them during interactive input
self
.
allow_kbdint
=
True
with
self
.
_maybe_use_pyrepl_as_stdin
():
self
.
cmdloop
()
self
.
allow_kbdint
=
False
break
except
KeyboardInterrupt
:
self
.
message
(
'--KeyboardInterrupt--'
)
def
_save_initial_file_mtime
(
self
,
frame
):
"""save the mtime of the all the files in the frame stack in the file mtime table
if they haven't been saved yet."""
while
frame
:
filename
=
frame
.
f_code
.
co_filename
if
filename
not
in
self
.
_file_mtime_table
:
try
:
self
.
_file_mtime_table
[
filename
]
=
os
.
path
.
getmtime
(
filename
)
except
Exception
:
pass
frame
=
frame
.
f_back
def
_validate_file_mtime
(
self
):
"""Check if the source file of the current frame has been modified.
If so, give a warning and reset the modify time to current."""
try
:
filename
=
self
.
curframe
.
f_code
.
co_filename
mtime
=
os
.
path
.
getmtime
(
filename
)
except
Exception
:
return
if
(
filename
in
self
.
_file_mtime_table
and
mtime
!=
self
.
_file_mtime_table
[
filename
]):
self
.
message
(
f"*** WARNING: file '
{
filename
}
' was edited, "
"running stale code until the program is rerun"
)
self
.
_file_mtime_table
[
filename
]
=
mtime
# Called before loop, handles display expressions
# Set up convenience variable containers
def
_show_display
(
self
):
displaying
=
self
.
displaying
.
get
(
self
.
curframe
)
if
displaying
:
for
expr
,
oldvalue
in
displaying
.
items
():
newvalue
=
self
.
_getval_except
(
expr
)
# check for identity first; this prevents custom __eq__ to
# be called at every loop, and also prevents instances whose
# fields are changed to be displayed
if
newvalue
is
not
oldvalue
and
newvalue
!=
oldvalue
:
displaying
[
expr
]
=
newvalue
self
.
message
(
'display %s: %s [old: %s]'
%
(
expr
,
self
.
_safe_repr
(
newvalue
,
expr
),
self
.
_safe_repr
(
oldvalue
,
expr
)))
def
_get_tb_and_exceptions
(
self
,
tb_or_exc
):
"""
Given a traceback or an exception, return a tuple of chained exceptions
and current traceback to inspect.
This will deal with selecting the right ``__cause__`` or ``__context__``
as well as handling cycles, and return a flattened list of exceptions we
can jump to with do_exceptions.
"""
_exceptions
=
[]
if
isinstance
(
tb_or_exc
,
BaseException
):
traceback
,
current
=
tb_or_exc
.
__traceback__
,
tb_or_exc
while
current
is
not
None
:
if
current
in
_exceptions
:
break
_exceptions
.
append
(
current
)
if
current
.
__cause__
is
not
None
:
current
=
current
.
__cause__
elif
(
current
.
__context__
is
not
None
and
not
current
.
__suppress_context__
):
current
=
current
.
__context__
if
len
(
_exceptions
)
>=
self
.
MAX_CHAINED_EXCEPTION_DEPTH
:
self
.
message
(
f"More than
{
self
.
MAX_CHAINED_EXCEPTION_DEPTH
}
"
" chained exceptions found, not all exceptions"
"will be browsable with `exceptions`."
)
break
else
:
traceback
=
tb_or_exc
return
tuple
(
reversed
(
_exceptions
)),
traceback
@
contextmanager
def
_hold_exceptions
(
self
,
exceptions
):
"""
Context manager to ensure proper cleaning of exceptions references
When given a chained exception instead of a traceback,
pdb may hold references to many objects which may leak memory.
We use this context manager to make sure everything is properly cleaned
"""
try
:
self
.
_chained_exceptions
=
exceptions
self
.
_chained_exception_index
=
len
(
exceptions
)
-
1
yield
finally
:
# we can't put those in forget as otherwise they would
# be cleared on exception change
self
.
_chained_exceptions
=
tuple
()
self
.
_chained_exception_index
=
0
def
_get_asyncio_task
(
self
):
try
:
task
=
asyncio
.
current_task
()
except
RuntimeError
:
task
=
None
return
task
def
interaction
(
self
,
frame
,
tb_or_exc
):
# Restore the previous signal handler at the Pdb prompt.
if
Pdb
.
_previous_sigint_handler
:
try
:
signal
.
signal
(
signal
.
SIGINT
,
Pdb
.
_previous_sigint_handler
)
except
ValueError
:
# ValueError: signal only works in main thread
pass
else
:
Pdb
.
_previous_sigint_handler
=
None
self
.
_current_task
=
self
.
_get_asyncio_task
()
_chained_exceptions
,
tb
=
self
.
_get_tb_and_exceptions
(
tb_or_exc
)
if
isinstance
(
tb_or_exc
,
BaseException
):
assert
tb
is
not
None
,
"main exception must have a traceback"
with
self
.
_hold_exceptions
(
_chained_exceptions
):
self
.
setup
(
frame
,
tb
)
# We should print the stack entry if and only if the user input
# is expected, and we should print it right before the user input.
# We achieve this by appending _pdbcmd_print_frame_status to the
# command queue. If cmdqueue is not exhausted, the user input is
# not expected and we will not print the stack entry.
self
.
cmdqueue
.
append
(
'_pdbcmd_print_frame_status'
)
self
.
_cmdloop
()
# If _pdbcmd_print_frame_status is not used, pop it out
if
self
.
cmdqueue
and
self
.
cmdqueue
[
-
1
]
==
'_pdbcmd_print_frame_status'
:
self
.
cmdqueue
.
pop
()
self
.
forget
()
def
displayhook
(
self
,
obj
):
"""Custom displayhook for the exec in default(), which prevents
assignment of the _ variable in the builtins.
"""
# reproduce the behavior of the standard displayhook, not printing None
if
obj
is
not
None
:
self
.
message
(
repr
(
obj
))
@
contextmanager
def
_enable_multiline_input
(
self
):
try
:
import
readline
except
ImportError
:
yield
return
def
input_auto_indent
():
last_index
=
readline
.
get_current_history_length
()
last_line
=
readline
.
get_history_item
(
last_index
)
if
last_line
:
if
last_line
.
isspace
():
# If the last line is empty, we don't need to indent
return
last_line
=
last_line
.
rstrip
(
'
\r
\n
'
)
indent
=
len
(
last_line
)
-
len
(
last_line
.
lstrip
())
if
last_line
.
endswith
(
":"
):
indent
+=
4
readline
.
insert_text
(
' '
*
indent
)
completenames
=
self
.
completenames
try
:
self
.
completenames
=
self
.
complete_multiline_names
readline
.
set_startup_hook
(
input_auto_indent
)
yield
finally
:
readline
.
set_startup_hook
()
self
.
completenames
=
completenames
return
def
_exec_in_closure
(
self
,
source
,
globals
,
locals
):
""" Run source code in closure so code object created within source
can find variables in locals correctly
returns True if the source is executed, False otherwise
"""
# Determine if the source should be executed in closure. Only when the
# source compiled to multiple code objects, we should use this feature.
# Otherwise, we can just raise an exception and normal exec will be used.
code
=
compile
(
source
,
"<string>"
,
"exec"
)
if
not
any
(
isinstance
(
const
,
CodeType
)
for
const
in
code
.
co_consts
):
return
False
# locals could be a proxy which does not support pop
# copy it first to avoid modifying the original locals
locals_copy
=
dict
(
locals
)
locals_copy
[
"__pdb_eval__"
]
=
{
"result"
:
None
,
View remainder of file in raw view
Footer
© 2026 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Community
Docs
Contact
You can’t perform that action at this time.
Back
|
FazBrowse Home
|
New Git URL