一个curl命令的python写法

获取响应数据,状态码,dns解析时间,连接时间,总请求时间,curl命令可以这样写:

[root@localhost ~]# echo -n {"data":;curl -s http://apis.haoservice.com/weather -w , "http_code":%{http_code}, "dns":%{time_namelookup}, "connect":%{time_connect}, "total":%{time_total}}
{"data":{"error_code":10001,"reason":"错误的请求KEY","result":null}, "http_code":200, "dns":0.050, "connect":0.079, "total":0.150}

用python如何实现类似功能?

使用 pycurl
先 pip install pycurl
然后执行以下脚本即可,兼容 Python 2.7 和 Python 3

#!/usr/bin/env python
# -*- coding: utf-8 -*- import os,sys
import time
import sys
import pycurl class joincontents: def __init__self: self.contents = def callbackself,curl: self.contents = self.contents + curl.decodeutf-8 def curlurlurl: t = joincontents c = pycurl.Curl c.setoptpycurl.WRITEFUNCTION,t.callback c.setoptpycurl.ENCODING, gzip c.setoptpycurl.URL,url c.perform NAMELOOKUP_TIME = c.getinfoc.NAMELOOKUP_TIME CONNECT_TIME = c.getinfoc.CONNECT_TIME PRETRANSFER_TIME = c.getinfoc.PRETRANSFER_TIME STARTTRANSFER_TIME = c.getinfoc.STARTTRANSFER_TIME TOTAL_TIME = c.getinfoc.TOTAL_TIME HTTP_CODE = c.getinfoc.HTTP_CODE SIZE_DOWNLOAD = c.getinfoc.SIZE_DOWNLOAD HEADER_SIZE = c.getinfoc.HEADER_SIZE SPEED_DOWNLOAD=c.getinfoc.SPEED_DOWNLOAD print"HTTP状态码:%s" %HTTP_CODE print"DNS解析时间:%.2f ms"%NAMELOOKUP_TIME*1000 print"建立连接时间:%.2f ms" %CONNECT_TIME*1000 print"准备传输时间:%.2f ms" %PRETRANSFER_TIME*1000 print"传输开始时间:%.2f ms" %STARTTRANSFER_TIME*1000 print"传输结束总时间:%.2f ms" %TOTAL_TIME*1000 print"下载数据包大小:%d bytes/s" %SIZE_DOWNLOAD print"HTTP头部大小:%d byte" %HEADER_SIZE print"平均下载速度:%d bytes/s" %SPEED_DOWNLOAD if __name__ == __main__: url = sys.argv[1] curlurlurl

Subprocess.Popencurl …

requests模块

发表评论

电子邮件地址不会被公开。 必填项已用*标注