Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6fb1e74

Browse files
committed
Fix ResourceWarning in asyncio.BaseSubprocessTransport
Issue #24763: Fix resource warnings when asyncio.BaseSubprocessTransport constructor fails, if subprocess.Popen raises an exception for example. Patch written by Martin Richard, test written by me.
1 parent 062759f commit 6fb1e74

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

Lib/asyncio/base_subprocess.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,13 @@ def __init__(self, loop, protocol, args, shell,
3535
self._pipes[2] = None
3636

3737
# Create the child process: set the _proc attribute
38-
self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
39-
stderr=stderr, bufsize=bufsize, **kwargs)
38+
try:
39+
self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
40+
stderr=stderr, bufsize=bufsize, **kwargs)
41+
except:
42+
self.close()
43+
raise
44+
4045
self._pid = self._proc.pid
4146
self._extra['subprocess'] = self._proc
4247

Lib/test/test_asyncio/test_subprocess.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import signal
22
import sys
33
import unittest
4+
import warnings
45
from unittest import mock
56

67
import asyncio
@@ -413,6 +414,20 @@ def kill_running():
413414
# the transport was not notified yet
414415
self.assertFalse(killed)
415416

417+
def test_popen_error(self):
418+
# Issue #24763: check that the subprocess transport is closed
419+
# when BaseSubprocessTransport fails
420+
with mock.patch('subprocess.Popen') as popen:
421+
exc = ZeroDivisionError
422+
popen.side_effect = exc
423+
424+
create = asyncio.create_subprocess_exec(sys.executable, '-c',
425+
'pass', loop=self.loop)
426+
with warnings.catch_warnings(record=True) as warns:
427+
with self.assertRaises(exc):
428+
self.loop.run_until_complete(create)
429+
self.assertEqual(warns, [])
430+
416431

417432
if sys.platform != 'win32':
418433
# Unix

0 commit comments

Comments
 (0)