Skip to content

Commit b407496

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

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

Lib/cProfile.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -98,22 +98,11 @@ 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

119108

@@ -192,10 +181,19 @@ def main():
192181
'__cached__': None,
193182
'__builtins__': __builtins__,
194183
}
184+
# cmd has to run in __main__ namespace (or imports from __main__ will
185+
# break). Clear __main__ and replace with the globals provided.
186+
import __main__
187+
# Save a reference to the current __main__ namespace so that we can
188+
# restore it after cmd completes.
189+
original_main = __main__.__dict__.copy()
190+
__main__.__dict__.update(globs)
195191

196192
try:
197-
runctx(code, globs, None, options.outfile, options.sort)
193+
runctx(code, __main__.__dict__, None, options.outfile, options.sort)
198194
except BrokenPipeError as exc:
195+
__main__.__dict__.clear()
196+
__main__.__dict__.update(original_main)
199197
# Prevent "Exception ignored" during interpreter shutdown.
200198
sys.stdout = None
201199
sys.exit(exc.errno)

0 commit comments

Comments
 (0)