device.py: fix _subprocess_Popen cleanup.

Every time gdbclient.py finishes it's giving this error:

Exception TypeError: 'must be type, not None' in <bound method
_subprocess_Popen.__del__ of <adb.device._subprocess_Popen object at
0x7fdd48e76850>> ignored

Basically super(_subprocess_Popen, self) was failing because at that
point _subprocess_Popen is None since global teardown had already
deleted the reference.

This fix saves local references to required global objects so that they
stick around until we're done with them. We may want to start looking
into making _subprocess_Popen a context manager instead, usage won't be
as convenient but __del__() does not scale to general use well. For now
though this CL seems to solve the problem for gdbclient.py.

Change-Id: I6c2a9fe0c108ae600cf05eb3b887d56959c7308e
diff --git a/python-packages/adb/device.py b/python-packages/adb/device.py
index e040cdf..ceb263d 100644
--- a/python-packages/adb/device.py
+++ b/python-packages/adb/device.py
@@ -212,6 +212,12 @@
 # Call this instead of subprocess.Popen(). Like _subprocess_check_output().
 class _subprocess_Popen(subprocess.Popen):
     def __init__(self, *args, **kwargs):
+        # __del__() can be called after global teardown has started, meaning
+        # the global references to _subprocess_Popen and the os module may
+        # no longer exist. We need to save local references to all global names
+        # used in __del__() to avoid this.
+        self.saved_class = _subprocess_Popen
+        self.saved_os = os
         # Save reference to helper so that it can be deleted once it is no
         # longer used.
         self.helper = _get_windows_unicode_helper(args[0])
@@ -219,9 +225,9 @@
                 *_get_subprocess_args(args, self.helper), **kwargs)
 
     def __del__(self, *args, **kwargs):
-        super(_subprocess_Popen, self).__del__(*args, **kwargs)
+        super(self.saved_class, self).__del__(*args, **kwargs)
         if self.helper:
-            os.remove(self.helper.name)
+            self.saved_os.remove(self.helper.name)
 
 
 class AndroidDevice(object):