Skip to content

Commit 3665a7f

Browse files
committed
Only modify __main__ in CLI invocation
1 parent 75a542e commit 3665a7f

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

Lib/cProfile.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -98,25 +98,13 @@ def run(self, cmd):
9898
return self.runctx(cmd, dict, dict)
9999

100100
def runctx(self, cmd, globals, locals):
101-
# cmd has to run in __main__ namespace (or imports from __main__ will
102-
# break). Clear __main__ and replace with the globals provided.
103-
import __main__
104-
# Save a reference to the current __main__ namespace so that we can
105-
# restore it after cmd completes.
106-
original_main = __main__.__dict__.copy()
107-
__main__.__dict__.clear()
108-
__main__.__dict__.update(globals)
109-
110101
self.enable()
111102
try:
112-
exec(cmd, __main__.__dict__, locals)
103+
exec(cmd, globals, locals)
113104
finally:
114105
self.disable()
115-
__main__.__dict__.clear()
116-
__main__.__dict__.update(original_main)
117106
return self
118107

119-
120108
# This method is more useful to profile a single function call.
121109
def runcall(self, func, /, *args, **kw):
122110
self.enable()
@@ -192,10 +180,19 @@ def main():
192180
'__cached__': None,
193181
'__builtins__': __builtins__,
194182
}
183+
# cmd has to run in __main__ namespace (or imports from __main__ will
184+
# break). Clear __main__ and replace with the globals provided.
185+
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()
189+
__main__.__dict__.update(globs)
195190

196191
try:
197-
runctx(code, globs, None, options.outfile, options.sort)
192+
runctx(code, __main__.__dict__, None, options.outfile, options.sort)
198193
except BrokenPipeError as exc:
194+
__main__.__dict__.clear()
195+
__main__.__dict__.update(original_main)
199196
# Prevent "Exception ignored" during interpreter shutdown.
200197
sys.stdout = None
201198
sys.exit(exc.errno)

0 commit comments

Comments
 (0)