python
1, Mac 系统自带的python路径
/System/Library/Frameworks/Python.framework/Version里面存放多个版本
可通过:启动python
import sys
print sys.path 查看路径
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
2, mac 里面可以启动idle新建.py 文件,然后打开cmd用Mac自带的 执行 python 路径/.py文件
windows里面可以用notepad++ 编写,然后 ctrl + f5配置一下,作为run
3,mac 不支持汉字支持
#! /usr/bin/env python
#! /usr/bin/env python
# coding=utf-8
import sys
import os
import urllib
import urllib2
import unittest
import json
import time
reload(sys)
sys.setdefaultencoding("utf-8")
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
def sendmail():
msg = MIMEMultipart()
#att = MIMEText(open(r'C:\Users\alice02.yang\Desktop\brandid.txt', 'rb').read(), 'base64', 'gb2312')
#att["Content-Type"] = 'application/octet-stream'
#att["Content-Disposition"] = 'attachment; filename="brandid.txt"'
#msg.attach(att)
strTo = ('zhihuiyang1990@163.com','xxx')
msg['to'] = ';'.join(strTo)
msg['from'] = 'zhihuiyang1990@163.com'
msg['subject'] = 'brandid'
try:
server = smtplib.SMTP()
server.connect('smtp.163.com')
server.login('zhihuiyang1990@163.com','yzh1990a1a1')
server.sendmail(msg['from'], strTo,msg.as_string())
server.quit()
print 'finish'
except Exception, e:
print str(e)
if __name__ == '__main__':
sendmail()
linux --> cmd 使用crontab -e
然后 编写 下午六点20发送 20 18 * * * cd /Users/vip/pythonTestScript; python testAutoSendMail.py 退出
对被反垃圾邮件网关隔离邮件放行的操作步骤:
开始→程序→附件→系统工具→计划任务→打开添加任务计划。进入任务计划向导。
利用“任务计划”,可以将任何脚本、程序或文档安排在某个最方便的时间运行。“任务计划”在每次启动 Windows XP 的时候启动并在后台运行。
5,连接数据库操作
linux 要安装MySQLdb插件
import MySQLdb
def conncur():
conn=MySQLdb.connect(host='10.1x',user='rx',passwd='ax',port=3306,charset='GBK')
cur=conn.cursor()
return conn,cur
def conSql():
try:
conn,cur=conncur()
cur.execute('drop database if exists vxl')
cur.execute('create database if not exists vixl')
conn.select_db('vix')
#sqlfile=open(r'D:\vipd.sql')
#sql=sqlfile.readlines()
#sqlfile.close()
#for line in sql:
#cur.execute(line)
#conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
if __name__ == '__main__':
conSql()
6,多线程
# coding:gbk
import time
import urllib
import urllib2
import threading
from Queue import Queue
from time import sleep
#THREAD_NUM = 10
#ONE_WORKER_NUM = 500
#LOOP_SLEEP = 0.01
THREAD_NUM = 100
ONE_WORKER_NUM = 10
LOOP_SLEEP = 0.5
PERF_TEST_URL=''
ERROR_NUM = 0
def get(url,para):
url_value = urllib.urlencode(para)
fullurl=url+'?'+url_value
print fullurl
data=urllib2.urlopen(fullurl,timeout=20)
json=data.read()
return json
def doWork(index):
t = threading.currentThread()
#print "["+t.name+" "+str(index)+"] "+PERF_TEST_URL
try:
url='xxxp'
para= build_para()
json = get(url,para)
print json
except urllib2.URLError, e:
print "["+t.name+" "+str(index)+"] "
print e
global ERROR_NUM
ERROR_NUM += 1
def working():
t = threading.currentThread()
print "["+t.name+"] Sub Thread Begin"
i = 0
while i < ONE_WORKER_NUM:
i += 1
doWork(i)
sleep(LOOP_SLEEP)
print "["+t.name+"] Sub Thread End"
def build_para():
para={}
para['mid']='123456789'
para['function']='testfunction'
para['appname']='testapp'
para['warehouse']='VIP_SH'
para['tag']='C10'
para['client']='ipad'
para['areaid']='103101'
para['mchannel']='10'
return para
def main():
t1 = time.time()
Threads = []
for i in range(THREAD_NUM):
t = threading.Thread(target=working, name="T"+str(i))
t.setDaemon(True)
Threads.append(t)
for t in Threads:
t.start()
for t in Threads:
t.join()
print "main thread end"
t2 = time.time()
print "========================================"
print "URL:", PERF_TEST_URL
print "task num:", THREAD_NUM, "*", ONE_WORKER_NUM, "=", THREAD_NUM*ONE_WORKER_NUM
print "total time cost:", t2-t1
print "per req time cost( sec):", (t2-t1) / (THREAD_NUM*ONE_WORKER_NUM)
print "req per sec:", 1 / ((t2-t1) / (THREAD_NUM*ONE_WORKER_NUM))
print "error num:", ERROR_NUM
if __name__ == "__main__":
main()
7,单元测试操作
写好TestCase,然后由TestLoader加载TestCase到TestSuite,然后由TextTestRunner来运行TestSuite,运行的结果保存在TextTestResult中,我们通过命令行或者unittest.main()执行时,main会调用TextTestRunner中的run来执行,或者我们可以直接通过TextTestRunner来执行用例。
import unittest
class TestCdi(unittest.TestCase):
def setUp(self):
conSql()
#------------------------across hit one-----------------------------
#------------------------hit Challenger-----------------------------
def testbroute_2(self):
if __name__ == '__main__':
unittest.main()
每个测试方法均以 开头,否则是不被unittest识别的
8,post/get请求操作
#! /usr/bin/env python
# coding=utf-8
import urllib2
import urllib
import httplib
import json
url='xxxx'
para={}
para={}
var={}
f1=open(r"C:\Users\alice02.yang\Desktop\my.txt",'w')
para["function"]="Recommend"
para["appName"]="ADS"
#var["mid"]="123456789"
var["warehouse"]="VIP_NH"
#var["tag"]="B"
var["mid"]="11111111111"
#var["client"]="iphone"
#var["areaid"]="103107"
#var["mchannel"]="1"
var["user_id"]="12345"
#var["version"]="2.11"
para["variables"]=var
url_v = urllib.urlencode(para)
url_value=url_v.replace("%27",'%22')
fullurl=url+'?'+url_value
headers = {"Content-Type":"application/x-www-form-urlencoded","Connection":"Keep-Alive","Referer":"http://10.19x"}
print fullurl
conn = httplib.HTTPConnection("10x");
conn.request("POST","xxxx",url_value,headers);
response = conn.getresponse()
print response.read()
f1.close()
conn.close()
import hashlib
import json
import unittest
import urllib2
def getmd5code(src):
#print src
m1 = hashlib.md5()
m1.update(src)
return m1.hexdigest()
9,连接redis集群操作
#! /usr/bin/env python
# coding=utf-8
import sys
import os
import json
import getopt
import urllib2
from urllib import urlopen
from rediscluster import StrictRedisCluster
reload(sys)
sys.setdefaultencoding( "utf-8" )
# URL = "xxxx"
# DATAURL = "xxxx"
# ticket = "ST-328962-"
# DELETE_DATA_URL = "".join([URL, "?ticket=", ticket, "&treeId=160"])
# INFO_DATA_URL = "".join([DATAURL, "?ticket=", ticket, "&key="])
URL = "xxx"
DATAURL = "xxxr"
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie','_const_cas_assertion_=ST-45'))
DELETE_DATA_URL = "".join([URL, "?treeId=117"])
INFO_DATA_URL = "".join([DATAURL, "?key="])
f1=open(r'C:\Users\alice02.yang\Desktop\ss\117mappingId.txt','w')
def redis_cluster(key,value):
print key
print value
redis_nodes = [{'host':'10.198.184.184','port':6379},
{'host':'10.198.xxx','port':6380},
{'host':'10.x','port':6379},
{'host':'10.x','port':6380},
{'host':'10.x','port':6379},
{'host':'10.x','port':6380}
]
try:
redisconn = StrictRedisCluster(startup_nodes=redis_nodes)
#rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
except Exception,e:
print "Connect Error!"
sys.exit(1)
try:
redisconn.hmset(key,value)
except:
pass
print "sssss"
print redisconn.hgetall(key)
def rank():
catIdList=[]
#print DELETE_DATA_URL
#content = urlopen(DELETE_DATA_URL).read()
content = opener.open(DELETE_DATA_URL).read()
print content
content = json.loads(content)
datas = content["data"];
#print datas
for data in datas:
for i in data['nodes']:
try:
for j in i['nodes'][0]['mappingCatIds']:
catIdList.append(str(j))
print i['nodes'][0]['mappingCatIds']
except:
pass
return catIdList
def getBigDataInfo(cat):
adict = {}
for i in cat:
warehouse=[""]
#warehouse=[""]
for wareh in warehouse:
key = str(i) + ":" + str(wareh) + ":3105"
print key
#print INFO_DATA_URL + key
bigDataInfo = urlopen(INFO_DATA_URL + key).read()
bigDataInfo = json.loads(bigDataInfo)
bigdatas = bigDataInfo["data"];
try:
print bigdatas["value"]
adict[key]=bigdatas["value"]
except:
pass
return adict
#for k in bigdatas["value"]:
#print k
#redis_cluster(key,k,bigdatas["value"][k])
def main():
cat = rank()
#cat=[7494,1018]
print cat
print >>f1,"\n".join(cat)
#adict = getBigDataInfo(cat)
#for key,value in adict.items():
#print key
#print value
#redis_cluster(key,value)
if __name__ == "__main__":
main()
10,excel表格操作
import xlrd
import json
data = xlrd.open_workbook(r'C:\Users\alice02.yang\Desktop\tt.xlsx')
table = data.sheet_by_name(u'Sheet1')
a=table.col_values(6)
b=table.col_values(7)
dics={}
result=[]
for i in range(len(a)):
dics={}
print a[i]
if len(a[i])==0:
break
dics['name']=a[i]
dics['value']=b[i]
print dics
result.append(dics)
print result
dict_res=json.dumps(result,ensure_ascii=False)
print dict_res.decode('utf-8').encode('gbk')
11,基本操作
异常
:=(,"w" fhwrite"这是一个测试文件,用于测试异常!!" :print"Error: 没有找到文件或读取文件失败"else fhclose
import os
import time
import datetime
overdueName=list()
oneDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 1))
oneDayAgoTimeStamp = int(time.mktime(oneDayAgo.timetuple()))
def del_files(path):
for root , dirs, files in os.walk(path):
for name in files:
if name.endswith(".xls"):
timeStr = name.split(".xls")[0].split("cdi_rule_")[1];
timeStrToInt = int(time.mktime(time.strptime(timeStr,'%Y-%m-%d')))
if timeStrToInt <= oneDayAgoTimeStamp:
overdueName.append(name)
if len(overdueName)>=10:
for temp in overdueName:
os.remove(os.path.join(path, temp))
print ("Delete File: " + os.path.join(path, temp))
if __name__ == "__main__":
#path = '/tmp'
path = 'E:'
del_files(path)
- Python 2.7.x 和 3.x 版本的语法区别
<__future__模块> Python 3.x引入了一些与Python 2不兼容的关键字和特性,在Python 2中,可以通过内置的__future__模块导入这些新内容.如果你希望在 ...
- 13本热门书籍免费送!(Python、SpingBoot、Entity Framework、Ionic、MySQL、深度学习、小程序开发等)
七月第一周,网易云社区联合清华大学出版社为大家送出13本数据分析以及移动开发的书籍(Python.SpingBoot.Entity Framework.Ionic.MySQL.深度学习.小程序开发等) ...
- python 2.7 学习笔记--day1--基础语句和语法
1. 用户交互 鉴于本小节十分的基础,变不多做赘述啦! 1.1 输出第一个程序:"Hello World !" 1.2 输出字符串,重点是去除字符串中的前后的空格,使用strip( ...
- Python基础学习参考(二):基本语法
一.基本语法 既然是学习一门语言,它肯定有区别与其它语言的语法规则,现在就来解释一下python的语法规则是什么? 注释:通过"#"可以对python进行注释,注意是单行注释,如果 ...
- Python 3 re模块3个括号相关的语法
(?aiLmsux) (One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches t ...
- Python之路1-变量、数据类型、循环语法
1.python语言介绍 编程语言主要从以下几个角度进行分类,编译型和解释型,静态语言和动态语言,强类型定义语言和弱类型定义语言. 编译和解释区别 编译器是把源程序的每一条语句都编译成机器语言,并保存 ...
- Python之路(第三十三篇) 网络编程:socketserver深度解析
一.socketserver 模块介绍 socketserver是标准库中的一个高级模块,用于网络客户端与服务器的实现.(version = "0.4") 在python2中写作S ...
- Python项目在Jenkins中的自动化测试实践(语法检查、单元测试,coverage(代码覆盖率)、自动打包)
原始链接:http://blog.csdn.net/a464057216/article/details/52934077 requirments OS: Ubuntu 14.04+ Gitlab 8 ...
- Python基础--正則表達式基本的语法以及re模块
正则是个非常牛逼的东西,python中当然也不会缺少. 所以今天的Python就跟大家一起讨论一下python中的re模块. re模块包括对正則表達式的支持. 什么是正则: 正則表達式是能够匹配文本片 ...
随机推荐
- java框架之SpringBoot(12)-消息及整合RabbitMQ
前言 概述 大多数应用中,可通过消息服务中间件来提升系统异步通信.扩展解耦的能力. 消息服务中两个重要概念:消息代理(message broker)和目的地(destination).当消息发送者发送 ...
- 大牛推荐的30本经典编程书籍,从Python到前端全系列。
注:为了方便阅读与收藏,我们也制作了30本书籍完整清单的Markdown.PDF版以及思维导图版,大家可以在实验楼公众号后台回复关键字"书籍推荐"获取. Python 系列(10本 ...
- git 如何删除已经add的文件
git rm --cached "文件" 参考: https://blog.csdn.net/kiss_the_sky/article/details/77921206
- std::bind学习
std::bind bind是对C++98标准中函数适配器bind1st/bind2nd的泛化和增强,可以适配任意的可调用对象,包括函数指针.函数引用.成员函数指针和函数对象. bind接受的第一个参 ...
- sublime----------快捷键的记录
1.鼠标选中多行,按下 Ctrl Shift L (Command Shift L) 即可同时编辑这些行: 2.鼠标选中自定义的多行,ctrl+鼠标左键
- JavaScript中的BOM和DOM
javascript组成: 1. ECMAScript 基本语法. 2. BOM (浏览器对象模型) 3. DOM (文档对象模型) 简单的说就是 BOM是浏览器对象模型,用来获取或设置浏览器的属性. ...
- Py't'hon之csv,ini&序列化,反序列化
1.csv文件简介 csv是一个被行分隔符,列分隔符划分成行和列的文本 csv不指定字符编码 行分隔符为\r\n,最后一行可以没有换行符 列分隔符常为逗号和制表符 每一行称之为record from ...
- 虚拟机centos7配置本地yum源
在虚拟机中要使用yum命令,就要先配置一下yum源,下面就分享一下这个过程: 1. 挂载iso到vmware,首先得确保CD/DVD连接到镜像.可以这样操作 2. 执行下面的命令 # mkdir /m ...
- C#简单的九九乘法表
for(int i=1;i<10;i++) { for(int j=1;j<=i;j++) { Console.Write("{0}*{1}={2}",j,i,i*j) ...
- 第九节 JS运动应用
多物体运动框架 多个物体同时运动 例子:多个Div,鼠标移入变宽 单定时器,存在问题 每个Div一个定时器 <!DOCTYPE html> <html lang="en&q ...