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)

1)python,现在用过的,后面推出每日练习语法与深度挖掘应用的更多相关文章

  1. Python 2.7.x 和 3.x 版本的语法区别

    <__future__模块> Python 3.x引入了一些与Python 2不兼容的关键字和特性,在Python 2中,可以通过内置的__future__模块导入这些新内容.如果你希望在 ...

  2. 13本热门书籍免费送!(Python、SpingBoot、Entity Framework、Ionic、MySQL、深度学习、小程序开发等)

    七月第一周,网易云社区联合清华大学出版社为大家送出13本数据分析以及移动开发的书籍(Python.SpingBoot.Entity Framework.Ionic.MySQL.深度学习.小程序开发等) ...

  3. python 2.7 学习笔记--day1--基础语句和语法

    1. 用户交互 鉴于本小节十分的基础,变不多做赘述啦! 1.1 输出第一个程序:"Hello World !" 1.2 输出字符串,重点是去除字符串中的前后的空格,使用strip( ...

  4. Python基础学习参考(二):基本语法

    一.基本语法 既然是学习一门语言,它肯定有区别与其它语言的语法规则,现在就来解释一下python的语法规则是什么? 注释:通过"#"可以对python进行注释,注意是单行注释,如果 ...

  5. Python 3 re模块3个括号相关的语法

    (?aiLmsux) (One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches t ...

  6. Python之路1-变量、数据类型、循环语法

    1.python语言介绍 编程语言主要从以下几个角度进行分类,编译型和解释型,静态语言和动态语言,强类型定义语言和弱类型定义语言. 编译和解释区别 编译器是把源程序的每一条语句都编译成机器语言,并保存 ...

  7. Python之路(第三十三篇) 网络编程:socketserver深度解析

    一.socketserver 模块介绍 socketserver是标准库中的一个高级模块,用于网络客户端与服务器的实现.(version = "0.4") 在python2中写作S ...

  8. Python项目在Jenkins中的自动化测试实践(语法检查、单元测试,coverage(代码覆盖率)、自动打包)

    原始链接:http://blog.csdn.net/a464057216/article/details/52934077 requirments OS: Ubuntu 14.04+ Gitlab 8 ...

  9. Python基础--正則表達式基本的语法以及re模块

    正则是个非常牛逼的东西,python中当然也不会缺少. 所以今天的Python就跟大家一起讨论一下python中的re模块. re模块包括对正則表達式的支持. 什么是正则: 正則表達式是能够匹配文本片 ...

随机推荐

  1. ts-loader 安装问题

    首先,有个问题:ts-loader是将typescript转成javascript,转成哪个版本的javascript版本? 查询到参考地址:http://morning.work/page/othe ...

  2. PyQt5信号、定时器及多线程

    信号 信号是用于界面自动变化的一个工具,原理是信号绑定了一个函数,当信号被触发时函数即被调用 举个例子 from PyQt5 import QtWidgets,QtCore from untitled ...

  3. 自动微分(AD)学习笔记

    1.自动微分(AD) 作者:李济深链接:https://www.zhihu.com/question/48356514/answer/125175491来源:知乎著作权归作者所有.商业转载请联系作者获 ...

  4. [js]js设计模式-构造函数模式

    构造函数模式 function WriteJsPerson(name,age) { this.name=name; //不用手动创建obj this.age = age; this.writeJs=f ...

  5. Python openpyxl、pandas操作Excel方法简介与具体实例

    本篇重点讲解windows系统下 Python3.5中第三方excel操作库-openpyxl: 其实Python第三方库有很多可以操作Excel,如:xlrd,xlwt,xlwings甚至注明的数据 ...

  6. python使用grpc调用rpc接口

    proto文件: syntax = "proto3"; package coupon; // //message UnsetUseC2URequest { // int64 bid ...

  7. C#中Abstract和Virtual(转载)

    在C#的学习中,容易混淆virtual方法和abstract方法的使用,现在来讨论一下二者的区别.二者都牵涉到在派生类中与override的配合使用. 一.Virtual方法(虚方法) virtual ...

  8. VCS

    timing check相关的, +notimingcheck命令,可以用在compile时,也可以用在run time的时候, 都是将检查timing的系统函数,都disable掉了, 加在comp ...

  9. nginx配置详细解析

    转自 http://blog.csdn.net/zhongguozhichuang/article/details/528168871.静态HTTP服务器 首先,Nginx是一个HTTP服务器,可以将 ...

  10. vue的一些感想

    如今vue2.0是主流,但是它的路由确实直接从1.0过来的,其中包括组件包括全局组件和局部组件,写好组件之后,我们就需要 使用路由,将组件关联起来,关联起来之后,然后我们才可以将组件的内容通过hash ...