Gaurav Sharma Gaurav Sharma - 3 months ago 54
Python Question

CURL alternative in Python

I have a cURL call that I use in PHP:


curl -i -H 'Accept: application/xml' -u login:key "https://app.streamsend.com/emails"


I need a way to do the same thing in Python. Is there an alternative to cURL in Python. I know of urllib but I'm a Python noob and have no idea how to use it.

Answer
import urllib2

manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')
handler = urllib2.HTTPBasicAuthHandler(manager)

director = urllib2.OpenerDirector()
director.add_handler(handler)

req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'})

result = director.open(req)
# result.read() will contain the data
# result.info() will contain the HTTP headers

# To get say the content-length header
length = result.info()['Content-Length']

Your cURL call using urllib2 instead. Completely untested.