如何实现CURL等效的python代码

时间:2014-01-03 11:18:11

标签: python curl

python中的CURL等价方法是什么? 例如在PHP中:

$url = "http://example.com/";
$params = "?param1=" + $param1;
$params += "&param2=" + $param2;
$url = $url + $params;

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,  $params);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, $httpReferer);
curl_exec($ch);
curl_close($ch);

1 个答案:

答案 0 :(得分:1)

你可以使用pycurl。以下是基本pycurl的示例:

#! /usr/bin/python

import sys
import pycurl

class Test:
    def __init__(self):
        self.contents = ''

    def body_callback(self, buf):
        self.contents = self.contents + buf

sys.stderr.write("Testing %s\n" % pycurl.version)

t = Test()
c = pycurl.Curl()
c.setopt(c.URL, 'http://curl.haxx.se/dev/')
c.setopt(c.WRITEFUNCTION, t.body_callback)
c.perform()
c.close()

print(t.contents)