Python杂记
python 2.7
先装easy install
https://pypi.Python.org/pypi/setuptools#downloads 可以下载,在win7 cmd下用python ez_setup.py安装
也可以装个IPython shell Http://arcHive.ipython.org/release/
后自动补全的Pyreadline https://pypi.python.org/pypi/pyreadline
提供http post支持的multipartposthandler https://pypi.python.org/packages/2.7/M/MultipartPostHandler2/
在windows cmd下 >easy_install MultipartPostHandler2-0.1.5-py2.7.egg
pip 安装和管理 Python 包的工具 , 是 easy_install 的一个替换品
https://pip.pypa.io/en/latest/installing.html >python get-pip.py
新的包格式wheel https://pypi.python.org/pypi/wheel >pip install --user wheel
http request https://pypi.python.org/pypi/requests/ >pip install requests
一些例子:
#!/usr/bin/python2.7
import sys
import os
import JSON
import MultipartPostHandler
import urllib2
import requests
import time
import telnetlib
bridgeip = '192.168.0.166'
targetlamp = []
base_url = 'http://'+bridgeip+'/api/'+username
config_url = base_url + '/config'
path = os.getcwd()
print('filepath = ' + path)
#使用MultipartPostHandler
def postBridge():
log('Posting reset firmware file to the bridge')
filepath = os.path.join(path, 'FirmwareBridge', 'reset', 'rel.fw') #looks in the directory ../<script execution dir>/FirmwareBridge/reset/ for rel.fw
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
params = {'fileupload' : open(filepath, 'rb')}
opener.open('http://'+bridgeip+'/updater', params)
log( 'Bridge is restarting ...')
time.sleep(60)
#使用requests
def setBridgeVersion(bridgeVersion):
log('Posting firmware file to the bridge')
filepath = os.path.join(path, 'FirmwareBridge', bridgeVersion, 'rel.fw')
#filepath = os.path.join(path, 'FirmwareBridge', bridgeVersion, 'prod.fw')
firmwareBridge = {'firmwarefile' : open(filepath, 'rb')}
fileuploadurl = 'http://'+bridgeip+'/updater'
response = requests.post(fileuploadurl, files=firmwareBridge)
print response.text
time.sleep(60)
#httpget,json操作
def fillLighsArray():
r = requests.get(base_url)
config = r.text
configjson = json.loads(config)
lights = json.dumps(configjson['lights'])
lightsjson = json.loads(lights)
for i in range(1,len(lightsjson)+1):
targetlamp.append(i)
#http put
def setPortalServices(set_value):
body = '{"portalservices":' + set_value + '}'
r = requests.put(config_url,body)
log( "Setting portal services to [" + set_value + "] : " + r.text)
检查ping结果
def pingHost(host):
p = subprocess.Popen("ping -n 1 "+ host,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True,
bufsize = 0)
(stdoutput,erroutput) = p.communicate()
regex = re.compile("Minimum = (\d+)ms, Maximum = (\d+)ms, Average = (\d+)ms", re.IGNORECASE)
print("find %d\n",len(regex.findall(stdoutput)))
if len(regex.findall(stdoutput)) > 0:
#print host+': Host Up!'
return True
else:
#print host+': Host Down!'
return False
相关文章