From: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com> Date: Wed, 29 Oct 2025 11:38:28 +0000 (+0000) Subject: gh-140741: Fix `profiling.sampling` handling of error raised by target (#140745) X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=d3aa5f689cddf6d58c2b988fd74e8bff2273e426;p=thirdparty%2FPython%2Fcpython.git gh-140741: Fix `profiling.sampling` handling of error raised by target (#140745) --- diff --git a/Lib/profiling/sampling/_sync_coordinator.py b/Lib/profiling/sampling/_sync_coordinator.py index 79e8858ca175..8716e6541047 100644 --- a/Lib/profiling/sampling/_sync_coordinator.py +++ b/Lib/profiling/sampling/_sync_coordinator.py @@ -175,14 +175,15 @@ def _execute_script(script_path: str, script_args: List[str], cwd: str) -> None: try: with open(script_path, 'rb') as f: source_code = f.read() - - # Compile and execute the script - code = compile(source_code, script_path, 'exec') - exec(code, {'__name__': '__main__', '__file__': script_path}) except FileNotFoundError as e: raise TargetError(f"Script file not found: {script_path}") from e except PermissionError as e: raise TargetError(f"Permission denied reading script: {script_path}") from e + + try: + # Compile and execute the script + code = compile(source_code, script_path, 'exec') + exec(code, {'__name__': '__main__', '__file__': script_path}) except SyntaxError as e: raise TargetError(f"Syntax error in script {script_path}: {e}") from e except SystemExit: diff --git a/Lib/test/test_profiling/test_sampling_profiler.py b/Lib/test/test_profiling/test_sampling_profiler.py index 59bc18b9bcf1..cbfb21d3512e 100644 --- a/Lib/test/test_profiling/test_sampling_profiler.py +++ b/Lib/test/test_profiling/test_sampling_profiler.py @@ -2080,6 +2080,22 @@ class TestSampleProfilerErrorHandling(unittest.TestCase): # Expected errors - we just want to test format validation pass + def test_script_error_treatment(self): + script_file = tempfile.NamedTemporaryFile("w", delete=False, suffix=".py") + script_file.write("open('nonexistent_file.txt')\n") + script_file.close() + self.addCleanup(os.unlink, script_file.name) + + result = subprocess.run( + [sys.executable, "-m", "profiling.sampling.sample", "-d", "1", script_file.name], + capture_output=True, + text=True, + ) + output = result.stdout + result.stderr + + self.assertNotIn("Script file not found", output) + self.assertIn("No such file or directory: 'nonexistent_file.txt'", output) + class TestSampleProfilerCLI(unittest.TestCase): def _setup_sync_mocks(self, mock_socket, mock_popen): diff --git a/Misc/NEWS.d/next/Library/2025-10-29-09-40-10.gh-issue-140741.L13UCV.rst b/Misc/NEWS.d/next/Library/2025-10-29-09-40-10.gh-issue-140741.L13UCV.rst new file mode 100644 index 000000000000..9fa8c561a03c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-10-29-09-40-10.gh-issue-140741.L13UCV.rst @@ -0,0 +1,2 @@ +Fix :func:`profiling.sampling.sample` incorrectly handling a +:exc:`FileNotFoundError` or :exc:`PermissionError`.