Skip to content

Commit 1dba378

Browse files
authored
bpo-22536 [3.6] Set filename in FileNotFoundError (#3305)
* [3.6] bpo-22536: Set the filename in FileNotFoundError. (GH-3194) Have the subprocess module set the filename in the FileNotFoundError exception raised on POSIX systems when the executable or cwd are missing. (cherry picked from commit 8621bb5) * bpo-22536 [3.6] (GH-3202) skip non-windows tests.
1 parent 703fdb8 commit 1dba378

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

Lib/subprocess.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,15 +1328,15 @@ def _execute_child(self, args, executable, preexec_fn, close_fds,
13281328
child_exec_never_called = (err_msg == "noexec")
13291329
if child_exec_never_called:
13301330
err_msg = ""
1331+
# The error must be from chdir(cwd).
1332+
err_filename = cwd
1333+
else:
1334+
err_filename = orig_executable
13311335
if errno_num != 0:
13321336
err_msg = os.strerror(errno_num)
13331337
if errno_num == errno.ENOENT:
1334-
if child_exec_never_called:
1335-
# The error must be from chdir(cwd).
1336-
err_msg += ': ' + repr(cwd)
1337-
else:
1338-
err_msg += ': ' + repr(orig_executable)
1339-
raise child_exception_type(errno_num, err_msg)
1338+
err_msg += ': ' + repr(err_filename)
1339+
raise child_exception_type(errno_num, err_msg, err_filename)
13401340
raise child_exception_type(err_msg)
13411341

13421342

Lib/test/test_subprocess.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1375,6 +1375,18 @@ def test_failed_child_execute_fd_leak(self):
13751375
fds_after_exception = os.listdir(fd_directory)
13761376
self.assertEqual(fds_before_popen, fds_after_exception)
13771377

1378+
@unittest.skipIf(mswindows, "behavior currently not supported on Windows")
1379+
def test_file_not_found_includes_filename(self):
1380+
with self.assertRaises(FileNotFoundError) as c:
1381+
subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
1382+
self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
1383+
1384+
@unittest.skipIf(mswindows, "behavior currently not supported on Windows")
1385+
def test_file_not_found_with_bad_cwd(self):
1386+
with self.assertRaises(FileNotFoundError) as c:
1387+
subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
1388+
self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
1389+
13781390

13791391
class RunFuncTestCase(BaseTestCase):
13801392
def run_python(self, code, **kwargs):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The subprocess module now sets the filename when FileNotFoundError
2+
is raised on POSIX systems due to the executable or cwd not being found.

0 commit comments

Comments
 (0)