]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-140741: Fix `profiling.sampling` handling of error raised by target (#140745)
authorStan Ulbrych <89152624+StanFromIreland@users.noreply.github.com>
Wed, 29 Oct 2025 11:38:28 +0000 (11:38 +0000)
committerGitHub <noreply@github.com>
Wed, 29 Oct 2025 11:38:28 +0000 (11:38 +0000)
Lib/profiling/sampling/_sync_coordinator.py
Lib/test/test_profiling/test_sampling_profiler.py
Misc/NEWS.d/next/Library/2025-10-29-09-40-10.gh-issue-140741.L13UCV.rst [new file with mode: 0644]

index 79e8858ca1752932cea9083c70f14e81a0cfc413..8716e65410479194a9f3118243caa1dc16957531 100644 (file)
@@ -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:
index 59bc18b9bcf14d891ec2b046442cc22e6927b397..cbfb21d3512eee3593876f5e9c0111b838f8ebd6 100644 (file)
@@ -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 (file)
index 0000000..9fa8c56
--- /dev/null
@@ -0,0 +1,2 @@
+Fix :func:`profiling.sampling.sample` incorrectly handling a
+:exc:`FileNotFoundError` or :exc:`PermissionError`.