Skip to content

Instantly share code, notes, and snippets.

@zacharyvoase
Created November 13, 2012 18:22
Show Gist options
  • Select an option

  • Save zacharyvoase/4067466 to your computer and use it in GitHub Desktop.

Select an option

Save zacharyvoase/4067466 to your computer and use it in GitHub Desktop.
Use curl to make requests from Python. License: http://unlicense.org/
"""
>>> response = curl('http://news.ycombinator.com/')
>>> response.status
200
>>> response.getheader('content-type')
'text/html; charset=utf-8'
>>> response.read(6)
'<html>'
>>> response.close()
"""
import httplib
import subprocess
import sys
def curl(*args):
command = 'curl -s -i'.split() + list(args)
pipe = subprocess.Popen(command, stdin=None, stdout=subprocess.PIPE,
stderr=sys.stderr)
# HTTPResponse expects a socket, then calls `makefile()` on it.
class mock_socket(object):
def makefile(self, *args, **kwargs):
return pipe.stdout
response = httplib.HTTPResponse(mock_socket())
response.begin() # read HTTP headers and status line.
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment