-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathkernprof.py
More file actions
executable file
·1439 lines (1278 loc) · 48.5 KB
/
kernprof.py
File metadata and controls
executable file
·1439 lines (1278 loc) · 48.5 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
#!/usr/bin/env python
"""
Script to conveniently run profilers on code in a variety of
circumstances.
To profile a script, decorate the functions of interest with
:py:deco:`profile <line_profiler.explicit_profiler.GlobalProfiler>`:
.. code:: bash
echo "if 1:
@profile
def main():
1 + 1
main()
" > script_to_profile.py
NOTE:
New in 4.1.0: Instead of relying on injecting :py:deco:`profile`
into the builtins you can now ``import line_profiler`` and use
:py:deco:`line_profiler.profile <line_profiler.explicit_profiler.GlobalProfiler>`
to decorate your functions. This allows the script to remain
functional even if it is not actively profiled. See
:py:mod:`!line_profiler` (:ref:`link <line-profiler-basic-usage>`) for
details.
Then run the script using :program:`kernprof`:
.. code:: bash
kernprof -b script_to_profile.py
By default this runs with the default :py:mod:`cProfile` profiler and
does not require compiled modules. Instructions to view the results will
be given in the output. Alternatively, adding :option:`!-v` to the
command line will write results to stdout.
To enable line-by-line profiling, :py:mod:`line_profiler` must be
available and compiled, and the :option:`!-l` argument should be added to
the :program:`kernprof` invocation:
.. code:: bash
kernprof -lb script_to_profile.py
NOTE:
New in 4.3.0: More code execution options are added:
* :command:`kernprof <options> -m some.module <args to module>`
parallels :command:`python -m` and runs the provided module as
:py:mod:`__main__`.
* :command:`kernprof <options> -c "some code" <args to code>`
parallels :command:`python -c` and executes the provided literal
code.
* :command:`kernprof <options> - <args to code>` parallels
:command:`python -` and executes literal code passed via the
:file:`stdin`.
See also
:doc:`kernprof invocations </manual/examples/example_kernprof>`.
For more details and options, refer to the CLI help.
To view the :program:`kernprof` help text run:
.. code:: bash
kernprof --help
which displays:
.. code::
usage: kernprof [-h] [-V] [--config CONFIG] [--no-config]
[--line-by-line [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]]
[--builtin [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]]
[-s SETUP] [-p {path/to/script | object.dotted.path}[,...]]
[--preimports [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]]
[--prof-imports [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]]
[-o OUTFILE] [-v] [-q]
[--rich [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]]
[-u UNIT]
[--skip-zero [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]]
[--summarize [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]]
[-i [OUTPUT_INTERVAL]]
{path/to/script | -m path.to.module | -c "literal code"} ...
Run and profile a python script or module.
positional arguments:
{path/to/script | -m path.to.module | -c "literal code"}
The python script file, module, or literal code to run
args Optional script arguments
options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
--config CONFIG Path to the TOML file, from the `tool.line_profiler.kernprof`
table of which to load defaults for the options. (Default:
'pyproject.toml')
--no-config Disable the loading of configuration files other than the
default one
profiling options:
--line-by-line [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]
Use the line-by-line profiler instead of cProfile. Implies
`--builtin`. (Default: False; short form: -l)
--builtin [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]
Put `profile` in the builtins. Use
`profile.enable()`/`.disable()` to toggle profiling,
`@profile` to decorate functions, or `with profile:` to
profile a section of code. (Default: False; short form: -b)
-s, --setup SETUP Path to the Python source file containing setup code to
execute before the code to profile. (Default: N/A)
-p, --prof-mod PROF_MOD
List of modules, functions and/or classes to profile specified
by their name or path. These profiling targets can be supplied
both as comma-separated items, or separately with multiple
copies of this flag. Packages are automatically recursed into
unless they are specified with `<pkg>.__init__`. Adding the
current script/module profiles the entirety of it. Only works
with line profiling (`-l`/`--line-by-line`). (Default: N/A;
pass an empty string to clear the defaults (or any `-p` target
specified earlier)
---preimports [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]
Instead of eagerly importing all profiling targets specified
via `-p` and profiling them, only profile those that are
directly imported in the profiled code. Only works with
line profiling (`-l`/`--line-by-line`). (Default: False)
Eagerly import all profiling targets specified via `-p` and
profile them, instead of only profiling those that are
directly imported in the profiled code. Only works with line
profiling (`-l`/`--line-by-line`). (Default: True)
--prof-imports [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]
If the script/module profiled is in `--prof-mod`, autoprofile
all its imports. Only works with line profiling (`-l`/`--line-
by-line`). (Default: False)
output options:
-o, --outfile OUTFILE
Save stats to OUTFILE. (Default:
'<script_or_module_name>.lprof' in line-profiling mode
(`-l`/`--line-by-line`); '<script_or_module_name>.prof'
otherwise)
-v, --verbose, --view
Increase verbosity level (default: 0). At level 1, view the
profiling results in addition to saving them; at level 2,
show other diagnostic info.
-q, --quiet Decrease verbosity level (default: 0). At level -1, disable
helpful messages (e.g. "Wrote profile results to <...>"); at
level -2, silence the stdout; at level -3, silence the stderr.
--rich [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]
Use rich formatting if viewing output. (Default: False; short
form: -r)
-u, --unit UNIT Output unit (in seconds) in which the timing info is
displayed. (Default: 1e-06 s)
--skip-zero [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]
Hide functions which have not been called. (Default: False;
short form: -z)
--summarize [Y[es] | N[o] | T[rue] | F[alse] | on | off | 1 | 0]
Print a summary of total function time. (Default: False)
-i, --output-interval [OUTPUT_INTERVAL]
Enables outputting of cumulative profiling results to OUTFILE
every OUTPUT_INTERVAL seconds. Uses the threading module.
Minimum value (and the value implied if the bare option is
given) is 1 s. (Default: 0 s (disabled))
NOTE:
New in 5.0.0: For more intuitive profiling behavior, profiling
targets in :option:`!--prof-mod` (except the profiled script/code)
are now:
* Eagerly pre-imported to be profiled (see
:py:mod:`line_profiler.autoprofile.eager_preimports`),
regardless of whether those imports directly occur in the profiled
script/module/code.
* Descended/Recursed into if they are packages; pass
``<pkg_name>.__init__`` instead of ``<pkg_name>`` to curtail
descent and limit profiling to classes and functions in the local
namespace of the :file:`__init__.py`.
To restore the old behavior, pass the :option:`!--no-preimports`
flag.
""" # noqa: E501
import atexit
import builtins
import functools
import os
import sys
import threading
import asyncio # NOQA
import concurrent.futures # NOQA
import contextlib
import shutil
import tempfile
import time
import warnings
from argparse import ArgumentParser
from io import StringIO
from operator import methodcaller
from runpy import run_module
from pathlib import Path
from pprint import pformat
from shlex import quote
from textwrap import indent, dedent
from types import MethodType, ModuleType, SimpleNamespace
# NOTE: This version needs to be manually maintained in
# line_profiler/line_profiler.py and line_profiler/__init__.py as well
__version__ = '5.0.2'
# Guard the import of cProfile such that 3.x people
# without lsprof can still use this script.
try:
from cProfile import Profile
except ImportError:
from profile import Profile # type: ignore[assignment,no-redef]
import line_profiler
from line_profiler.cli_utils import (
add_argument,
get_cli_config,
get_python_executable as _python_command, # Compatibility
positive_float,
short_string_path,
)
from line_profiler.profiler_mixin import ByCountProfilerMixin
from line_profiler._logger import Logger
from line_profiler import _diagnostics as diagnostics
DIAGNOSITICS_VERBOSITY = 2
def execfile(filename, globals=None, locals=None):
"""Python 3.x doesn't have :py:func:`execfile` builtin"""
with open(filename, 'rb') as f:
exec(compile(f.read(), filename, 'exec'), globals, locals)
# =====================================
class ContextualProfile(ByCountProfilerMixin, Profile):
"""A subclass of :py:class:`Profile` that adds a context manager
for Python 2.5 with: statements and a decorator.
"""
def __init__(self, *args, **kwds):
super(ByCountProfilerMixin, self).__init__(*args, **kwds)
self.enable_count = 0
def __call__(self, func):
return self.wrap_callable(func)
def enable_by_count(self, subcalls=True, builtins=True):
"""Enable the profiler if it hasn't been enabled before."""
if self.enable_count == 0:
self.enable(subcalls=subcalls, builtins=builtins)
self.enable_count += 1
def disable_by_count(self):
"""Disable the profiler if the number of disable requests matches the
number of enable requests.
"""
if self.enable_count > 0:
self.enable_count -= 1
if self.enable_count == 0:
self.disable()
# FIXME: `profile.Profile` is fundamentally incompatible with the
# by-count paradigm we use, as it can't be `.enable()`-ed nor
# `.disable()`-ed
class RepeatedTimer:
"""
Background timer for outputting file every ``n`` seconds.
Adapted from [SO474528]_.
References:
.. [SO474528] https://stackoverflow.com/questions/474528/execute-function-every-x-seconds/40965385#40965385
""" # noqa: E501
def __init__(self, interval, dump_func, outfile):
self._timer = None
self.interval = interval
self.dump_func = dump_func
self.outfile = outfile
self.is_running = False
self.next_call = time.time()
self.start()
def _run(self):
self.is_running = False
self.start()
self.dump_func(self.outfile)
def start(self):
if not self.is_running:
self.next_call += self.interval
self._timer = threading.Timer(
self.next_call - time.time(), self._run
)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
def find_module_script(module_name, *, static=True, exit_on_error=True):
"""Find the path to the executable script for a module or package."""
from line_profiler.autoprofile.util_static import modname_to_modpath
from importlib.util import find_spec
def resolve_module_path(mod_name): # type: (str) -> str | None
try:
mod_spec = find_spec(mod_name)
except ImportError:
return None
if not mod_spec:
return None
fname = mod_spec.origin # type: str | None
if fname and os.path.exists(fname):
return fname
get_module_path = modname_to_modpath if static else resolve_module_path
for suffix in '.__main__', '':
fname = get_module_path(module_name + suffix)
if fname:
return fname
msg = f'Could not find module `{module_name}`'
if exit_on_error:
print(msg, file=sys.stderr)
raise SystemExit(1)
else:
raise ModuleNotFoundError(msg)
def find_script(script_name, *, exit_on_error=True):
"""Find the script.
If the input is not a file, then :envvar:`PATH` will be searched.
"""
if os.path.isfile(script_name):
return script_name
path = os.getenv('PATH', os.defpath).split(os.pathsep)
for dir in path:
if dir == '':
continue
fn = os.path.join(dir, script_name)
if os.path.isfile(fn):
return fn
msg = f'Could not find script {script_name!r}'
if exit_on_error:
print(msg, file=sys.stderr)
raise SystemExit(1)
else:
raise FileNotFoundError(msg)
def _normalize_profiling_targets(targets):
"""
Normalize the parsed :option:`!--prof-mod` by:
* Normalizing file paths with :py:func:`find_script()`, and
subsequently to absolute paths.
* Splitting non-file paths at commas into (presumably) file paths
and/or dotted paths.
* Allowing paths specified earlier to be invalidated by an empty
string.
* Removing duplicates.
"""
def find(path):
try:
path = find_script(path, exit_on_error=False)
except FileNotFoundError:
return None
return os.path.abspath(path)
results = {}
for chunk in targets:
if not chunk:
results.clear()
continue
filename = find(chunk)
if filename is not None:
results.setdefault(filename)
continue
for subchunk in chunk.split(','):
filename = find(subchunk)
results.setdefault(subchunk if filename is None else filename)
return list(results)
class _restore:
"""
Restore a collection like :py:data:`sys.path` after running code
which potentially modifies it.
"""
def __init__(self, obj, getter, setter):
self.obj = obj
self.setter = setter
self.getter = getter
self.old = None
def __enter__(self):
assert self.old is None
self.old = self.getter(self.obj)
def __exit__(self, *_, **__):
self.setter(self.obj, self.old)
self.old = None
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with self:
return func(*args, **kwargs)
return wrapper
@classmethod
def sequence(cls, seq):
"""
Example
-------
>>> l = [1, 2, 3]
>>>
>>> with _restore.sequence(l):
... print(l)
... l.append(4)
... print(l)
... l[:] = 5, 6
... print(l)
...
[1, 2, 3]
[1, 2, 3, 4]
[5, 6]
>>> l
[1, 2, 3]
"""
def set_list(orig, copy):
orig[:] = copy
return cls(seq, methodcaller('copy'), set_list)
@classmethod
def mapping(cls, mpg):
"""
Example
-------
>>> d = {1: 2}
>>>
>>> with _restore.mapping(d):
... print(d)
... d[2] = 3
... print(d)
... d.clear()
... d.update({1: 4, 3: 5})
... print(d)
...
{1: 2}
{1: 2, 2: 3}
{1: 4, 3: 5}
>>> d
{1: 2}
"""
def set_mapping(orig, copy):
orig.clear()
orig.update(copy)
return cls(mpg, methodcaller('copy'), set_mapping)
@classmethod
def instance_dict(cls, obj):
"""
Example
-------
>>> class Obj:
... def __init__(self, x, y):
... self.x, self.y = x, y
...
... def __repr__(self):
... return 'Obj({0.x!r}, {0.y!r})'.format(self)
...
>>>
>>> obj = Obj(1, 2)
>>>
>>> with _restore.instance_dict(obj):
... print(obj)
... obj.x, obj.y, obj.z = 4, 5, 6
... print(obj, obj.z)
...
Obj(1, 2)
Obj(4, 5) 6
>>> obj
Obj(1, 2)
>>> hasattr(obj, 'z')
False
"""
return cls.mapping(vars(obj))
def pre_parse_single_arg_directive(args, flag, sep='--'):
"""
Pre-parse high-priority single-argument directives like
:option:`!-m module` to emulate the behavior of
:command:`python [...]`.
Examples
--------
>>> import functools
>>> pre_parse = functools.partial(pre_parse_single_arg_directive,
... flag='-m')
Normal parsing:
>>> pre_parse(['foo', 'bar', 'baz'])
(['foo', 'bar', 'baz'], None, [])
>>> pre_parse(['foo', 'bar', '-m', 'baz'])
(['foo', 'bar'], 'baz', [])
>>> pre_parse(['foo', 'bar', '-m', 'baz', 'foobar'])
(['foo', 'bar'], 'baz', ['foobar'])
Erroneous case:
>>> pre_parse(['foo', 'bar', '-m'])
Traceback (most recent call last):
...
ValueError: argument expected for the -m option
Prevent erroneous consumption of the flag by passing it `'--'`:
>>> pre_parse(['foo', '--', 'bar', '-m', 'baz'])
(['foo', '--'], None, ['bar', '-m', 'baz'])
>>> pre_parse(['foo', '-m', 'spam',
... 'eggs', '--', 'bar', '-m', 'baz'])
(['foo'], 'spam', ['eggs', '--', 'bar', '-m', 'baz'])
"""
args = list(args)
pre = []
post = []
try:
i_sep = args.index(sep)
except ValueError: # No such element
pass
else:
pre[:] = args[:i_sep]
post[:] = args[i_sep + 1 :]
pre_pre, arg, pre_post = pre_parse_single_arg_directive(pre, flag)
if arg is None:
assert not pre_post
return pre_pre + [sep], arg, post
else:
return pre_pre, arg, [*pre_post, sep, *post]
try:
i_flag = args.index(flag)
except ValueError: # No such element
return args, None, []
if i_flag == len(args) - 1: # Last element
raise ValueError(f'argument expected for the {flag} option')
args, thing, post_args = args[:i_flag], args[i_flag + 1], args[i_flag + 2 :]
return args, thing, post_args
def no_op(*_, **__) -> None:
pass
def _add_core_parser_arguments(parser):
"""
Add the core kernprof args to a
:py:class:`~argparse.ArgumentParser`.
"""
default = get_cli_config('kernprof')
add_argument(
parser, '-V', '--version', action='version', version=__version__
)
add_argument(
parser,
'--config',
help='Path to the TOML file, from the '
'`tool.line_profiler.kernprof` table of which to load '
'defaults for the options. '
f'(Default: {short_string_path(default.path)!r})',
)
add_argument(
parser,
'--no-config',
action='store_const',
dest='config',
const=False,
help='Disable the loading of configuration files other than the default one',
)
prof_opts = parser.add_argument_group('profiling options')
add_argument(
prof_opts,
'-l',
'--line-by-line',
action='store_true',
help='Use the line-by-line profiler instead of cProfile. '
'Implies `--builtin`. '
f'(Default: {default.conf_dict["line_by_line"]})',
)
add_argument(
prof_opts,
'-b',
'--builtin',
action='store_true',
help='Put `profile` in the builtins. '
'Use `profile.enable()`/`.disable()` to '
'toggle profiling, '
'`@profile` to decorate functions, '
'or `with profile:` to profile a section of code. '
f'(Default: {default.conf_dict["builtin"]})',
)
if default.conf_dict['setup']:
def_setupfile = repr(default.conf_dict['setup'])
else:
def_setupfile = 'N/A'
add_argument(
prof_opts,
'-s',
'--setup',
help='Path to the Python source file containing setup '
'code to execute before the code to profile. '
f'(Default: {def_setupfile})',
)
if default.conf_dict['prof_mod']:
def_prof_mod = repr(default.conf_dict['prof_mod'])
else:
def_prof_mod = 'N/A'
add_argument(
prof_opts,
'-p',
'--prof-mod',
action='append',
help='List of modules, functions and/or classes to profile '
'specified by their name or path. These profiling targets '
'can be supplied both as comma-separated items, or '
'separately with multiple copies of this flag. Packages '
'are automatically recursed into unless they are specified '
'with `<pkg>.__init__`. Adding the current script/module '
'profiles the entirety of it. Only works with line '
'profiling (`-l`/`--line-by-line`). '
f'(Default: {def_prof_mod}; '
'pass an empty string to clear the defaults (or any `-p` '
'target specified earlier))',
)
add_argument(
prof_opts,
'--preimports',
action='store_true',
help='Eagerly import all profiling targets specified via '
'`-p` and profile them, instead of only profiling those '
'that are directly imported in the profiled code. '
'Only works with line profiling (`-l`/`--line-by-line`). '
f'(Default: {default.conf_dict["preimports"]})',
)
add_argument(
prof_opts,
'--prof-imports',
action='store_true',
help='If the script/module profiled is in `--prof-mod`, '
'autoprofile all its imports. '
'Only works with line profiling (`-l`/`--line-by-line`). '
f'(Default: {default.conf_dict["prof_imports"]})',
)
out_opts = parser.add_argument_group('output options')
if default.conf_dict['outfile']:
def_outfile = repr(default.conf_dict['outfile'])
else:
def_outfile = (
"'<script_or_module_name>.lprof' in line-profiling mode "
'(`-l`/`--line-by-line`); '
"'<script_or_module_name>.prof' otherwise"
)
add_argument(
out_opts,
'-o',
'--outfile',
help=f'Save stats to OUTFILE. (Default: {def_outfile})',
)
add_argument(
out_opts,
'-v',
'--verbose',
'--view',
action='count',
default=default.conf_dict['verbose'],
help='Increase verbosity level '
f'(default: {default.conf_dict["verbose"]}). '
'At level 1, view the profiling results in addition to '
'saving them; '
'at level 2, show other diagnostic info.',
)
add_argument(
out_opts,
'-q',
'--quiet',
action='count',
default=0,
help='Decrease verbosity level '
f'(default: {default.conf_dict["verbose"]}). '
'At level -1, disable '
'helpful messages (e.g. "Wrote profile results to <...>"); '
'at level -2, silence the stdout; '
'at level -3, silence the stderr.',
)
add_argument(
out_opts,
'-r',
'--rich',
action='store_true',
help='Use rich formatting if viewing output. '
f'(Default: {default.conf_dict["rich"]})',
)
add_argument(
out_opts,
'-u',
'--unit',
type=positive_float,
help='Output unit (in seconds) in which '
'the timing info is displayed. '
f'(Default: {default.conf_dict["unit"]} s)',
)
add_argument(
out_opts,
'-z',
'--skip-zero',
action='store_true',
help='Hide functions which have not been called. '
f'(Default: {default.conf_dict["skip_zero"]})',
)
add_argument(
out_opts,
'--summarize',
action='store_true',
help='Print a summary of total function time. '
f'(Default: {default.conf_dict["summarize"]})',
)
if default.conf_dict['output_interval']:
def_out_int = f'{default.conf_dict["output_interval"]} s'
else:
def_out_int = '0 s (disabled)'
add_argument(
out_opts,
'-i',
'--output-interval',
type=int,
const=1,
nargs='?',
help='Enables outputting of cumulative profiling results '
'to OUTFILE every OUTPUT_INTERVAL seconds. '
'Uses the threading module. '
'Minimum value (and the value implied if the bare option '
f'is given) is 1 s. (Default: {def_out_int})',
)
def _build_parsers(args=None):
parser_kwargs = {
'description': 'Run and profile a python script.',
}
if args is None:
args = sys.argv[1:]
# Special cases: `kernprof [...] -m <module>` or
# `kernprof [...] -c <script>` should terminate the parsing of all
# subsequent options
if '-m' in args and '-c' in args:
special_mode = min(['-c', '-m'], key=args.index)
elif '-m' in args:
special_mode = '-m'
else:
special_mode = '-c'
args, thing, post_args = pre_parse_single_arg_directive(args, special_mode)
if special_mode == '-m':
module, literal_code = thing, None
else:
module, literal_code = None, thing
if module is literal_code is None: # Normal execution
(real_parser,) = parsers = [ArgumentParser(**parser_kwargs)]
help_parser = None
else:
# We've already consumed the `-m <module>`, so we need a dummy
# parser for generating the help text;
# but the real parser should not consume the `options.script`
# positional arg, and it it got the `--help` option, it should
# hand off the the dummy parser
real_parser = ArgumentParser(add_help=False, **parser_kwargs)
real_parser.add_argument('-h', '--help', action='store_true')
help_parser = ArgumentParser(**parser_kwargs)
parsers = [real_parser, help_parser]
for parser in parsers:
_add_core_parser_arguments(parser)
if parser is help_parser or module is literal_code is None:
add_argument(
parser,
'script',
metavar='{path/to/script | -m path.to.module | -c "literal code"}',
help='The python script file, module, or literal code to run',
)
add_argument(
parser, 'args', nargs='...', help='Optional script arguments'
)
special_info = {
'module': module,
'literal_code': literal_code,
'post_args': post_args,
'args': args,
}
return real_parser, help_parser, special_info
def _parse_arguments(
real_parser, help_parser, special_info, args, exit_on_error
):
module = special_info['module']
literal_code = special_info['literal_code']
post_args = special_info['post_args']
# Hand off to the dummy parser if necessary to generate the help
# text
try:
options = SimpleNamespace(**vars(real_parser.parse_args(args)))
except SystemExit as e:
# If `exit_on_error` is true, let `SystemExit` bubble up and
# kill the interpretor;
# else, catch and handle it more gracefully
# (Note: can't use `ArgumentParser(exit_on_error=False)` in
# Python 3.8)
if exit_on_error:
raise
elif e.code:
raise RuntimeError from None
else:
return
# TODO: make flags later where appropriate
options.dryrun = diagnostics.NO_EXEC
options.static = diagnostics.STATIC_ANALYSIS
if help_parser and getattr(options, 'help', False):
help_parser.print_help()
if exit_on_error:
raise SystemExit(0)
else:
return
# Parse the provided config file (if any), and resolve the values
# of the un-specified options
try:
del options.help
except AttributeError:
pass
default = get_cli_config('kernprof', options.config)
options.config = default.path
for key, default in default.conf_dict.items():
if getattr(options, key, None) is None:
setattr(options, key, default)
# Add in the pre-partitioned arguments cut off by `-m <module>` or
# `-c <script>`
options.args += post_args
if module is not None:
options.script = module
tempfile_source_and_content = None
if literal_code is not None:
tempfile_source_and_content = 'command', literal_code
elif options.script == '-' and not module:
tempfile_source_and_content = 'stdin', sys.stdin.read()
# Handle output
options.verbose -= options.quiet
options.debug = (
diagnostics.DEBUG or options.verbose >= DIAGNOSITICS_VERBOSITY
)
logger_kwargs = {'name': 'kernprof'}
logger_kwargs['backend'] = 'auto'
if options.debug:
# Debugging forces the stdlib logger
logger_kwargs['verbose'] = 2
logger_kwargs['backend'] = 'stdlib'
elif options.verbose > -1:
logger_kwargs['verbose'] = 1
else:
logger_kwargs['verbose'] = 0
logger_kwargs['stream'] = {
'format': '[%(name)s %(asctime)s %(levelname)s] %(message)s',
}
# Reinitialize the diagnostic logs, we are very likely the main script.
diagnostics.log = Logger(**logger_kwargs)
if options.rich:
try:
import rich # noqa: F401
except ImportError:
options.rich = False
diagnostics.log.debug('`rich` not installed, unsetting --rich')
diagnostics.log.debug(
f'Loaded configs from {short_string_path(options.config)!r}'
)
return options, tempfile_source_and_content
@_restore.sequence(sys.argv)
@_restore.sequence(sys.path)
@_restore.instance_dict(diagnostics)
def main(args=None, *, exit_on_error=True):
"""
Runs the command line interface
Note:
To help with traceback formatting, the deletion of temporary
files created during execution may be deferred to when the
interpreter exits.
"""
real_parser, help_parser, special_info = _build_parsers(args=args)
args = special_info['args']
module = special_info['module']
options, tempfile_source_and_content = _parse_arguments(
real_parser, help_parser, special_info, args, exit_on_error
)
if module is not None:
diagnostics.log.debug(f'Profiling module: {module}')
elif tempfile_source_and_content:
diagnostics.log.debug(
f'Profiling script read from: {tempfile_source_and_content[0]}'
)
else:
diagnostics.log.debug(
f'Profiling script: {short_string_path(options.script)!r}'
)
with contextlib.ExitStack() as stack:
enter = stack.enter_context
if options.verbose < -1: # Suppress stdout
devnull = enter(open(os.devnull, mode='w'))
enter(contextlib.redirect_stdout(devnull))
if options.verbose < -2: # Suppress stderr
enter(contextlib.redirect_stderr(devnull))
# Instead of relying on `tempfile.TemporaryDirectory`, manually
# manage a tempdir to ensure that files exist at
# traceback-formatting time if needs be
options.tmpdir = tmpdir = tempfile.mkdtemp()
if diagnostics.KEEP_TEMPDIRS:
cleanup = no_op
else:
cleanup = functools.partial(
_remove,
tmpdir,
recursive=True,
missing_ok=True,
)
if tempfile_source_and_content:
try:
_write_tempfile(*tempfile_source_and_content, options)
except Exception:
# Tempfile creation failed, delete the tempdir ASAP
cleanup()
raise
try:
_main_profile(options, module, exit_on_error)
except BaseException:
# Defer deletion to after the traceback has been formatted
# if needs be
if os.listdir(tmpdir):
atexit.register(cleanup)
else: # Empty tempdir, just delete it
cleanup()
raise
else: # Execution succeeded, delete the tempdir ASAP
cleanup()
def _touch_tempfile(*args, **kwargs):
"""
Wrapper around :py:func:`tempfile.mkstemp()` which drops and closes
the integer handle (which we don't need and may cause issues on some