Skip to content

Commit e6d50bd

Browse files
committed
Avoid leaking cProfile scope into profiled code
1 parent 3665a7f commit e6d50bd

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

Lib/cProfile.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -183,16 +183,12 @@ def main():
183183
# cmd has to run in __main__ namespace (or imports from __main__ will
184184
# break). Clear __main__ and replace with the globals provided.
185185
import __main__
186-
# Save a reference to the current __main__ namespace so that we can
187-
# restore it after cmd completes.
188-
original_main = __main__.__dict__.copy()
186+
__main__.__dict__.clear()
189187
__main__.__dict__.update(globs)
190188

191189
try:
192190
runctx(code, __main__.__dict__, None, options.outfile, options.sort)
193191
except BrokenPipeError as exc:
194-
__main__.__dict__.clear()
195-
__main__.__dict__.update(original_main)
196192
# Prevent "Exception ignored" during interpreter shutdown.
197193
sys.stdout = None
198194
sys.exit(exc.errno)
@@ -202,4 +198,8 @@ def main():
202198

203199
# When invoked as main program, invoke the profiler on a script
204200
if __name__ == '__main__':
205-
main()
201+
# Since the code we run might need to modify __main__, we need to ensure
202+
# that cProfile's main function is run under some other namespace, so we
203+
# reimport and execute the main function separately
204+
import cProfile
205+
cProfile.main()

0 commit comments

Comments
 (0)