Created
November 13, 2012 18:22
-
-
Save zacharyvoase/4067466 to your computer and use it in GitHub Desktop.
Use curl to make requests from Python. License: http://unlicense.org/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| >>> 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