Download and decompress gzipped file in memory?

You need to seek to the beginning of compressedFile after writing to it but before passing it to gzip.GzipFile(). Otherwise it will be read from the end by gzip module and will appear as an empty file to it. See below: #! /usr/bin/env python import urllib2 import StringIO import gzip baseURL = “https://www.kernel.org/pub/linux/docs/man-pages/” filename = … Read more

How do I wrap a string in a file in Python?

For Python 2.x, use the StringIO module. For example: >>> from cStringIO import StringIO >>> f = StringIO(‘foo’) >>> f.read() ‘foo’ I use cStringIO (which is faster), but note that it doesn’t accept Unicode strings that cannot be encoded as plain ASCII strings. (You can switch to StringIO by changing “from cStringIO” to “from StringIO”.) … Read more

how do I clear a stringio object?

TL;DR Don’t bother clearing it, just create a new one—it’s faster. The method Python 2 Here’s how I would find such things out: >>> from StringIO import StringIO >>> dir(StringIO) [‘__doc__’, ‘__init__’, ‘__iter__’, ‘__module__’, ‘close’, ‘flush’, ‘getvalue’, ‘isatty’, ‘next’, ‘read’, ‘readline’, ‘readlines’, ‘seek’, ‘tell’, ‘truncate’, ‘write’, ‘writelines’] >>> help(StringIO.truncate) Help on method truncate in module … Read more

Extracting a zipfile to memory?

extractall extracts to the file system, so you won’t get what you want. To extract a file in memory, use the ZipFile.read() method. If you really need the full content in memory, you could do something like: def extract_zip(input_zip): input_zip=ZipFile(input_zip) return {name: input_zip.read(name) for name in input_zip.namelist()}

Retrieving the output of subprocess.call() [duplicate]

If you have Python version >= 2.7, you can use subprocess.check_output which basically does exactly what you want (it returns standard output as string). Simple example (linux version, see note): import subprocess print subprocess.check_output([“ping”, “-c”, “1”, “8.8.8.8”]) Note that the ping command is using linux notation (-c for count). If you try this on Windows … Read more