Skip to content

Commit d3aa5f6

Browse files
gh-140741: Fix profiling.sampling handling of error raised by target (#140745)
1 parent 02202c1 commit d3aa5f6

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

Lib/profiling/sampling/_sync_coordinator.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,14 +175,15 @@ def _execute_script(script_path: str, script_args: List[str], cwd: str) -> None:
175175
try:
176176
with open(script_path, 'rb') as f:
177177
source_code = f.read()
178-
179-
# Compile and execute the script
180-
code = compile(source_code, script_path, 'exec')
181-
exec(code, {'__name__': '__main__', '__file__': script_path})
182178
except FileNotFoundError as e:
183179
raise TargetError(f"Script file not found: {script_path}") from e
184180
except PermissionError as e:
185181
raise TargetError(f"Permission denied reading script: {script_path}") from e
182+
183+
try:
184+
# Compile and execute the script
185+
code = compile(source_code, script_path, 'exec')
186+
exec(code, {'__name__': '__main__', '__file__': script_path})
186187
except SyntaxError as e:
187188
raise TargetError(f"Syntax error in script {script_path}: {e}") from e
188189
except SystemExit:

Lib/test/test_profiling/test_sampling_profiler.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2080,6 +2080,22 @@ def test_valid_output_formats(self):
20802080
# Expected errors - we just want to test format validation
20812081
pass
20822082

2083+
def test_script_error_treatment(self):
2084+
script_file = tempfile.NamedTemporaryFile("w", delete=False, suffix=".py")
2085+
script_file.write("open('nonexistent_file.txt')\n")
2086+
script_file.close()
2087+
self.addCleanup(os.unlink, script_file.name)
2088+
2089+
result = subprocess.run(
2090+
[sys.executable, "-m", "profiling.sampling.sample", "-d", "1", script_file.name],
2091+
capture_output=True,
2092+
text=True,
2093+
)
2094+
output = result.stdout + result.stderr
2095+
2096+
self.assertNotIn("Script file not found", output)
2097+
self.assertIn("No such file or directory: 'nonexistent_file.txt'", output)
2098+
20832099

20842100
class TestSampleProfilerCLI(unittest.TestCase):
20852101
def _setup_sync_mocks(self, mock_socket, mock_popen):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`profiling.sampling.sample` incorrectly handling a
2+
:exc:`FileNotFoundError` or :exc:`PermissionError`.

0 commit comments

Comments
 (0)