Issue #13781: Fix GzipFile to work with os.fdopen()'d file objects.
diff --git a/Lib/gzip.py b/Lib/gzip.py
index 2bcb4db..8fdac83 100644
--- a/Lib/gzip.py
+++ b/Lib/gzip.py
@@ -88,8 +88,12 @@
if fileobj is None:
fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
if filename is None:
- if hasattr(fileobj, 'name'): filename = fileobj.name
- else: filename = ''
+ # Issue #13781: os.fdopen() creates a fileobj with a bogus name
+ # attribute. Avoid saving this in the gzip header's filename field.
+ if hasattr(fileobj, 'name') and fileobj.name != '<fdopen>':
+ filename = fileobj.name
+ else:
+ filename = ''
if mode is None:
if hasattr(fileobj, 'mode'): mode = fileobj.mode
else: mode = 'rb'
diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py
index 573879e..a28cd34 100644
--- a/Lib/test/test_gzip.py
+++ b/Lib/test/test_gzip.py
@@ -274,6 +274,14 @@
d = f.read()
self.assertEqual(d, data1 * 50, "Incorrect data in file")
+ def test_fileobj_from_fdopen(self):
+ # Issue #13781: Creating a GzipFile using a fileobj from os.fdopen()
+ # should not embed the fake filename "<fdopen>" in the output file.
+ fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
+ with os.fdopen(fd, "wb") as f:
+ with gzip.GzipFile(fileobj=f, mode="w") as g:
+ self.assertEqual(g.name, "")
+
def test_main(verbose=None):
test_support.run_unittest(TestGzip)