├── README.md ├── args_kwargs.py ├── args_unpacking.py ├── binary_search.py ├── bing_photos.py ├── check_ip.py ├── checkfile.py ├── closure.py ├── conf └── demo.conf ├── create_variable.py ├── decorator.py ├── def_scope.py ├── excel_demo.py ├── fib.py ├── for.py ├── hasattr.py ├── me.py ├── method.py ├── niu.py ├── niuniu.py ├── property.py ├── read_write_conf.py ├── save_excel_to_mysql.py ├── save_remote_image.py ├── scope.py ├── sendMail.py ├── singleton.py ├── static └── cropped-13887362_13887362_1347773771848.jpg ├── string_letters.py ├── sys_argv.py ├── test_mysqlclient.py ├── test_redis.py ├── testmongo.py ├── testpillow.py ├── testrequests.py ├── wechat-ledongli.py ├── window.py └── yun.py /README.md: -------------------------------------------------------------------------------- 1 | # learn-python 2 | 本人边学习Python3,边把一些小脚本(自己写的和网上找的)经过本机测试后然后同步到github上,供初学者下载研究,欢迎fork,也欢迎提交新的Python小脚本,特别是一些有趣好玩的小程序!有什么问题可以通过Issues讨论,喜欢的话点Star或分享给别人哦! 3 | 4 | 学习Python3记录博客: 5 | http://blog.tanteng.me/category/develop/python3/ 6 | 7 | 注:IDE是PyCharm4.5,Python版本是3.4.3 8 | 9 | 欢迎大家提交好的学习Python3的脚本,我会合并进来! 10 | -------------------------------------------------------------------------------- /args_kwargs.py: -------------------------------------------------------------------------------- 1 | # encoding:utf-8 2 | 3 | # -*- Python3可变参数 -*- 4 | 5 | import webbrowser 6 | 7 | def alias(*args, **kwargs): 8 | print('args=', args) 9 | print('kwargs=', kwargs) 10 | return 11 | 12 | alias(3, 23, 3, 3,a='hello',b=3,c='C') 13 | 14 | """ 15 | 输出: 16 | args= (3, 23, 3, 3) 17 | kwargs= {'b': 3, 'c': 'C', 'a': 'hello'} 18 | 19 | 小结: 20 | *args表示任何多个无名参数,它是一个tuple 21 | **kwargs表示关键字参数,它是一个dict 22 | """ 23 | 24 | # 具体参考资料 25 | webbrowser.open('http://www.tantengvip.com/2015/07/python-args-kwargs/', 1) 26 | -------------------------------------------------------------------------------- /args_unpacking.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 使用tupple或dict传参的技巧 4 | 5 | def product(a, b): 6 | print(str(a) + '*' + str(b)) 7 | return a * b 8 | 9 | argument_tuple = (1, 1) 10 | argument_dict = {'a': 1, 'b': 1} 11 | 12 | print(product(*argument_tuple)) # 这里用*解析tupple类型的变量作为product的参数 13 | print(product(**{'b':4,'a':3})) # 这里用**解析dict类型的变量作为product的参数 14 | -------------------------------------------------------------------------------- /binary_search.py: -------------------------------------------------------------------------------- 1 | # encoding:utf-8 2 | 3 | # -*- Python二分查找算法 -*- 4 | import sys 5 | 6 | def binarySearch(l, t): 7 | low, high = 0, len(l) - 1 8 | while low < high: 9 | print(low, high) 10 | mid = int((low + high) / 2) 11 | if l[mid] > t: 12 | high = mid 13 | elif l[mid] < t: 14 | low = mid + 1 15 | else: 16 | return mid 17 | return False 18 | 19 | if __name__ == '__main__': 20 | l = [1, 4, 12, 45, 66, 99, 120, 444] 21 | print(binarySearch(l, 12)) 22 | print(binarySearch(l, 1)) 23 | print(binarySearch(l, 13)) -------------------------------------------------------------------------------- /bing_photos.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # -*- coding:utf-8 -*- 4 | 5 | # -*- author:arron ni-*- 6 | 7 | # python3抓取bing主页所有背景图片 8 | 9 | import urllib.request 10 | import re 11 | import sys 12 | import os 13 | 14 | 15 | def get_bing_backphoto(): 16 | if os.path.exists('photos') == False: 17 | os.mkdir('photos') 18 | 19 | for i in range(0, 30): 20 | 21 | url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx=' + str(i) + '&n=1&nc=1361089515117&FORM=HYLH1' 22 | 23 | html = urllib.request.urlopen(url).read() 24 | 25 | if html == 'null': 26 | print('open & read bing error!') 27 | 28 | sys.exit(-1) 29 | 30 | html = html.decode('utf-8') 31 | 32 | reg = re.compile('"url":"(.*?)","urlbase"', re.S) 33 | 34 | text = re.findall(reg, html) 35 | 36 | # http://s.cn.bing.net/az/hprichbg/rb/LongJi_ZH-CN8658435963_1366x768.jpg 37 | 38 | for imgurl in text: 39 | right = imgurl.rindex('/') 40 | 41 | name = imgurl.replace(imgurl[:right + 1], '') 42 | 43 | savepath = 'photos/' + name 44 | 45 | urllib.request.urlretrieve(imgurl, savepath) 46 | 47 | print(name + ' save success!') 48 | 49 | 50 | get_bing_backphoto() -------------------------------------------------------------------------------- /check_ip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf-8 3 | 4 | import urllib.request 5 | import re 6 | import sys 7 | 8 | def ISIP(s): 9 | return len([i for i in s.split('.') if (0<= int(i)<= 255)])== 4 10 | 11 | def URL(ip): 12 | uip = urllib.request.urlopen('http://wap.ip138.com/ip.asp?ip='+ip) 13 | fip = uip.read() 14 | rip = re.compile("
查询结果:(.*)
") 15 | result = rip.findall(fip) 16 | print("%s\t %s" % (ip, result[0])) 17 | 18 | 19 | def DO(domain): 20 | url = urllib.request.urlopen('http://wap.ip138.com/ip.asp?ip='+domain) 21 | f = url.read().decode('utf-8') 22 | r = re.compile('
查询结果:(.*)
') 23 | result = r.findall(f) 24 | #print type(result) 25 | for i in result: 26 | print("%s %s %s" % (domain, i[0], i[1])) 27 | 28 | if __name__ == "__main__": 29 | if len(sys.argv) < 2: 30 | print("请输入IP地址或者域名 (例如:192.168.1.1 / www.baidu.com)") 31 | sys.exit() 32 | INPUT=sys.argv[1] 33 | if not re.findall('(\d{1,3}\.){3}\d{1,3}',INPUT): 34 | if re.findall('(\w+\.)?(\w+)(\.\D+){1,2}',INPUT) : 35 | DOMAIN=INPUT 36 | DO(DOMAIN) 37 | else: 38 | print("输入的IP地址和域名格式不对!") 39 | else: 40 | if ISIP(INPUT) : 41 | IPADDRESS=INPUT 42 | URL(IPADDRESS) 43 | else: 44 | print("IP 地址不合法,请重新输入!") 45 | -------------------------------------------------------------------------------- /checkfile.py: -------------------------------------------------------------------------------- 1 | import sys # Import the Modules 2 | import os # Import the Modules 3 | 4 | # Readfile Functions which open the file that is passed to the script 5 | 6 | def readfile(filename): 7 | print(filename) 8 | f = open(filename, 'r') 9 | line = f.read() 10 | print(line) 11 | 12 | 13 | def main(): 14 | filename = '' 15 | if len(sys.argv) == 2: # Check the arguments passed to the script 16 | filename = sys.argv[1] # The filename is the first argument 17 | if not os.path.isfile(filename): # Check the File exists 18 | print('[-] ' + filename + ' does not exist.') 19 | exit(0) 20 | if not os.access(filename, os.R_OK): # Check you can read the file 21 | print('[-] ' + filename + ' access denied') 22 | exit(0) 23 | else: 24 | print('[-] Usage: ' + str(sys.argv[0]) + ' ') # Print usage if not all parameters passed/Checked 25 | exit(0) 26 | print('[+] Reading from : ' + filename) # Display Message and read the file contents 27 | readfile(filename) 28 | 29 | if __name__ == '__main__': 30 | main() -------------------------------------------------------------------------------- /closure.py: -------------------------------------------------------------------------------- 1 | def hellocounter (name): 2 | count=0 #PYTHON 2.x 中,要写count=[0] 3 | def counter(): 4 | nonlocal count #PYTHON 2.x 中,此行和下一行要换成count[0]+=1 5 | count+=1 6 | print('Hello,',name,',',count,' access!')#PYTHON 2.x 中请自觉换成str(count[0]) 7 | return counter 8 | 9 | hello = hellocounter('ma6174') 10 | hello() 11 | hello() 12 | hello() 13 | 14 | ''' 15 | 执行结果 16 | >>> hello() 17 | Hello, ma6174 , 1 access! 18 | >>> hello() 19 | Hello, ma6174 , 2 access! 20 | >>> hello() 21 | Hello, ma6174 , 3 access! 22 | ''' 23 | ##为什么PYTHON 2.x中不直接写count而用list?这是python2的一个bug,如果用count话,会报这样一个错误: 24 | ##UnboundLocalError: local variable 'count' referenced before assignment. 25 | 26 | def make_adder(addend): 27 | def adder(augend): 28 | return augend + addend 29 | return adder 30 | 31 | p = make_adder(23) 32 | q = make_adder(44) 33 | 34 | print(p(100)) 35 | print(q(100)) 36 | -------------------------------------------------------------------------------- /conf/demo.conf: -------------------------------------------------------------------------------- 1 | #demo.conf文件内容: 2 | 3 | [sec_a] 4 | a_key1 = 20 5 | a_key2 = 10 6 | 7 | [sec_b] 8 | b_key1 = 121 9 | b_key2 = b_value2 10 | b_key3 = $r 11 | b_key4 = 127.0.0.1 12 | 13 | [website] 14 | url = http://www.tantengvip.com -------------------------------------------------------------------------------- /create_variable.py: -------------------------------------------------------------------------------- 1 | """ 2 | 演示Python如何动态创建变量 3 | """ 4 | 5 | pages = {} 6 | 7 | for page in range(1, 50): 8 | """ 9 | 这里想创建变量page1 = 1, page2 = 2, page3 = 3,... 10 | """ 11 | pages[page] = page 12 | 13 | print(pages[1]) 14 | print(pages[2]) 15 | -------------------------------------------------------------------------------- /decorator.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | # 定义一个装饰器 4 | def mydecorator(func): 5 | def wrapper(*args,**kw): 6 | print('hi,now is:') 7 | return func(*args,**kw) 8 | return wrapper 9 | 10 | # 使用装饰器 11 | @mydecorator 12 | def now(): 13 | print('2015-12-9') 14 | 15 | now() 16 | 17 | """ 18 | D:\learn-python>python decorator.py 19 | hi,now is: 20 | 2015-12-9 21 | 22 | 关于装饰器的具体概念,参见: 23 | http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000 24 | """ 25 | -------------------------------------------------------------------------------- /def_scope.py: -------------------------------------------------------------------------------- 1 | def bar(self, y): 2 | return self.x + y 3 | 4 | 5 | class Foo(object): 6 | def __init__(self, x): 7 | self.x = x 8 | 9 | bar = bar; 10 | 11 | 12 | foo = Foo(333); 13 | print(foo.bar(3)) 14 | 15 | #result:336 -------------------------------------------------------------------------------- /excel_demo.py: -------------------------------------------------------------------------------- 1 | import tablib 2 | headers = ('lie1', 'lie2', 'lie3', 'lie4', 'lie5') 3 | mylist = [('23','23','34','23','34'),('sadf','23','sdf','23','fsad')] 4 | mylist = tablib.Dataset(*mylist, headers=headers) 5 | with open('excel.xlsx', 'wb') as f: 6 | f.write(mylist.xlsx) -------------------------------------------------------------------------------- /fib.py: -------------------------------------------------------------------------------- 1 | def fib(max): 2 | n, a, b = 0, 0, 1 3 | while n < max: 4 | yield b 5 | a, b = b, a + b 6 | n = n + 1 7 | 8 | for i in fib(30): 9 | print(i) -------------------------------------------------------------------------------- /for.py: -------------------------------------------------------------------------------- 1 | """优化前""" 2 | for item in items: 3 | if is_for_sale(item): 4 | cost = compute_cost(item) 5 | if cost <= wallet.money: 6 | buy(item) 7 | 8 | """优化后""" 9 | for item in items: 10 | if not is_for_sale(item): 11 | continue 12 | cost = compute_cost(item) 13 | if cost > wallet.money: 14 | continue 15 | buy(item) -------------------------------------------------------------------------------- /hasattr.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Python hasattr判断是否存在属性 4 | 5 | class Test: 6 | 7 | product11 = ['d'] 8 | 9 | def __init__(self): 10 | pass 11 | 12 | def product(self, a, b): 13 | return a * b 14 | 15 | def is_exists(self): 16 | print(hasattr(self, 'product')) 17 | 18 | 19 | test = Test() 20 | test.is_exists() 21 | 22 | 23 | """ 24 | dir(test): 25 | ['__doc__', '__init__', '__module__', 'is_exists', 'product', 'product11'] 26 | """ -------------------------------------------------------------------------------- /me.py: -------------------------------------------------------------------------------- 1 | # Python dict 2 | me = { 3 | 'name': 'tanteng', 4 | 'age': 25, 5 | 'sex': 'man', 6 | 'city': 'Wuhan', 7 | 'college': 'WUST', 8 | 'profession': 'Computer Science and Technology', 9 | 'language': ['PHP', 'JavaScript', 'MySQL', 'Redis', 'MongoDB', 'Python'], 10 | 'website': 'http://www.tantengvip.com', 11 | 'email': 'tanteng@gmail.com' 12 | } 13 | -------------------------------------------------------------------------------- /method.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Python面向对象:类,类的方法,类方法,静态方法 4 | 5 | class Person(object): 6 | def __init__(self): 7 | print('init') 8 | 9 | @staticmethod 10 | def sayHello(hi): 11 | if hi is None: 12 | hi = 'hello' 13 | print(hi) 14 | 15 | @classmethod 16 | def hi(cls,msg): 17 | print(msg) 18 | print(dir(cls)) 19 | 20 | # 一般类的方法 21 | def hobby(self,hobby): 22 | print(hobby) 23 | 24 | # 调用静态方法,不用实例化 25 | Person.sayHello('hi') 26 | Person.hi('Hi!') 27 | 28 | # 实例化类调用普通方法,__init__在这里触发 29 | person = Person() 30 | person.hobby('football') 31 | 32 | 33 | """ 34 | 输出: 35 | hi 36 | Hi! 37 | ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof_ 38 | _', '__str__', '__subclasshook__', '__weakref__', 'hi', 'hobby', 'sayHello'] 39 | init 40 | football 41 | 42 | 其中def hi(cls)这个类方法,cls表示类自身,所以输出跟dir(person)是一样的。 43 | 44 | classmethod:类方法 45 | staticmethod:静态方法 46 | 47 | 在python中,静态方法和类方法都是可以通过类对象和类对象实例访问。但是区别是: 48 | 49 | 1.@classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。 50 | 类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。 51 | 52 | 2.普通对象方法至少需要一个self参数,代表类对象实例 53 | 54 | 3.类方法有类变量cls传入,从而可以用cls做一些相关的处理。并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。 55 | 对于类方法,可以通过类来调用,就像C.f(),有点类似C++中的静态方法, 也可以通过类的一个实例来调用,就像C().f(),这里C(),写成这样之后它就是类的一个实例了。 56 | 57 | 4.静态方法则没有,它基本上跟一个全局函数相同,一般来说用的很少 58 | """ -------------------------------------------------------------------------------- /niu.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # 列举一副牌所有牌型为牛牛的情况 4 | 5 | __author__ = 'tanteng' 6 | 7 | import itertools, sys 8 | 9 | 10 | # 初始化一副牌(除去大小王) 11 | def cards(): 12 | cards = {'黑桃A': 1, '红桃A': 1, '方块A': 1, '梅花A': 1} 13 | card_type = ['黑桃', '红桃', '方块', '梅花'] 14 | 15 | for c_type in card_type: 16 | for no in range(2, 11): 17 | cards[c_type + str(no)] = no 18 | 19 | for name in ['J', 'Q', 'K']: 20 | cards[c_type + name] = 10 21 | 22 | return cards 23 | 24 | 25 | # 从一副牌取5张牌所有排列 26 | def all_cases(cards): 27 | return list(itertools.combinations(cards, 5)) 28 | 29 | 30 | if __name__ == '__main__': 31 | cards = cards() 32 | all_cases = all_cases(cards) 33 | 34 | print(len(all_cases)) 35 | 36 | for case in all_cases: 37 | temp_name = list(case) 38 | temp_value = [] 39 | for ca in case: 40 | temp_value.append(cards[ca]) 41 | 42 | sums = sum(temp_value) 43 | if sums % 10 == 0: 44 | s_cases = list(itertools.combinations(temp_name, 3)) 45 | for s_case in s_cases: 46 | temp_name2 = list(s_case) 47 | temp_value2 = [] 48 | for s_ca in s_case: 49 | temp_value2.append(cards[s_ca]) 50 | 51 | sumc = sum(temp_value2) 52 | if sumc % 10 == 0: 53 | print(temp_name) 54 | break 55 | -------------------------------------------------------------------------------- /niuniu.py: -------------------------------------------------------------------------------- 1 | # 列举出所有牌型为牛牛的情况 2 | # author:tanteng 3 | import itertools,sys 4 | 5 | #初始化数据 6 | cards = list(itertools.combinations([1,2,3,4,5,6,7,8,9,10,11,12,13],5)) 7 | print(len(cards)) 8 | card_name = {1:'A',2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:'J',12:'Q',13:'K'} 9 | Count = 0 10 | 11 | #判断牌型是否为牛牛 12 | def is_niuniu(card=None): 13 | sums = 0 14 | card_copy = list(map(check_card,list(card))) 15 | sums = sum(card_copy) 16 | 17 | if sums%10 == 0:#五张牌相加是10的倍数 18 | new_card = list(itertools.permutations(card,3))#从五张牌取3张进行排列 19 | for new_c in new_card: 20 | new_c = list(new_c) 21 | new_c = list(map(check_card,new_c)) 22 | summ = sum(new_c) 23 | if (summ%10 == 0):#如果有任意三张牌是10的倍数 24 | #print(summ) 25 | print(list(map(show_card, card))) 26 | global Count 27 | Count = Count+1 28 | break 29 | 30 | #显示对应的牌的名称 31 | def show_card(card): 32 | return card_name[card]; 33 | 34 | #将11,12,13替换成10 35 | def check_card(card): 36 | if card>10: 37 | return 10 38 | else: 39 | return card 40 | 41 | if __name__ == '__main__': 42 | for card in cards: 43 | is_niuniu(card) 44 | 45 | print(Count) -------------------------------------------------------------------------------- /property.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 属性装饰器 4 | class Student(object): 5 | @property 6 | def score(self): 7 | return self._score 8 | 9 | @score.setter 10 | def score(self, value): 11 | if not isinstance(value,int): 12 | raise ValueError('必须输入数字!') 13 | if value<0 or value>100: 14 | raise ValueError('必须大于0小于100!') 15 | self._score = value 16 | 17 | s = Student() 18 | s.score = 101 19 | print(s.score) 20 | -------------------------------------------------------------------------------- /read_write_conf.py: -------------------------------------------------------------------------------- 1 | # encoding:utf-8 2 | 3 | # !/usr/bin/env python 4 | 5 | # -*- Python读写conf格式配置文件 -*- 6 | 7 | __author__ = 'tanteng' 8 | 9 | 10 | import configparser 11 | import webbrowser 12 | 13 | # 返回config对象 14 | conf = configparser.ConfigParser() 15 | conf.read('./conf/demo.conf', 'utf-8') 16 | 17 | # 读取配置文件 18 | def readConf(): 19 | # 得到所有sections 20 | sections = conf.sections() 21 | print(sections) 22 | 23 | # 得到sec_a,sec_b的设置项 24 | options_sec_a = conf.options('sec_a') 25 | print(options_sec_a) 26 | 27 | options_sec_b = conf.options('sec_b') 28 | print(options_sec_b) 29 | 30 | # 得到sec_a,sec_b的设置键值对 31 | items_sec_a = conf.items('sec_a') 32 | print(items_sec_a) 33 | 34 | items_sec_b = conf.items('sec_b') 35 | print(items_sec_b) 36 | 37 | # 得到具体某个section某个option的值 38 | sec_a_key1 = conf.get('sec_a','a_key1') 39 | print(sec_a_key1) 40 | 41 | readConf() 42 | 43 | ''' 44 | readConf()运行结果: 45 | 46 | ['sec_a', 'sec_b'] 47 | ['a_key1', 'a_key2'] 48 | ['b_key1', 'b_key2', 'b_key3', 'b_key4'] 49 | [('a_key1', '20'), ('a_key2', '10')] 50 | [('b_key1', '121'), ('b_key2', 'b_value2'), ('b_key3', '$r'), ('b_key4', '127.0.0.1')] 51 | 20 52 | ''' 53 | 54 | # 写配置文件 55 | def writeConf(): 56 | # 更新某个section某个option的值 57 | conf.set('sec_a','a_key1','100') # 最后一个参数必须是string类型 58 | value = conf.get('sec_a','a_key1') 59 | print(value) # 打印结果看是否设置成功 60 | 61 | conf.add_section('new_section') 62 | conf.set('new_section','new_option_name','new_option_value') 63 | 64 | new_sections = conf.sections() 65 | 66 | # 检测是否新增section和新增设置项成功 67 | print(new_sections) 68 | print(conf.get('new_section','new_option_name')) 69 | 70 | 71 | writeConf() 72 | 73 | ''' 74 | writeConf()运行结果: 75 | 76 | 100 77 | ['sec_a', 'sec_b', 'website', 'new_section'] 78 | new_option_value 79 | tantengdeMacBook-Pro:learn-python tanteng$ 80 | ''' 81 | 82 | # 更多Python3入门文章,读取网址配置跳转,现学现用 83 | 84 | def jump(): 85 | url = conf.get('website','url') 86 | webbrowser.open(url) 87 | 88 | jump() 89 | -------------------------------------------------------------------------------- /save_excel_to_mysql.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import xlrd 3 | import MySQLdb 4 | import os 5 | import logging 6 | import shutil 7 | import sys 8 | 9 | 10 | def main(path): 11 | """ 12 | 打开目录遍历excel文件并存储到mysql 13 | """ 14 | files = os.listdir(path) 15 | for file in files: 16 | save_file(path + '/' + file, file) 17 | print(file) 18 | 19 | 20 | def save_file(file, filename): 21 | """ 22 | 打开excel文件 23 | """ 24 | try: 25 | book = xlrd.open_workbook(file) 26 | sheet = book.sheet_by_index(0) 27 | except Exception as e: 28 | logging.info('错误:{0} 文件:{1}'.format(e, file)) 29 | shutil.copy2(file, './error' + filename) 30 | return False 31 | row_nums = sheet.nrows 32 | col_nums = sheet.ncols 33 | 34 | page = False # 是否分几次插入 35 | 36 | data = [] 37 | if row_nums < 2: 38 | return False 39 | if col_nums not in [23, 25]: # 两种excel格式,一个23列,一个25列 40 | return False 41 | 42 | for rownumber in range(1, row_nums): 43 | if page is True: 44 | data = [] 45 | values = sheet.row_values(rownumber) 46 | values.insert(0, 0) 47 | if values[1] == '': 48 | return False 49 | 50 | # 不同形式表格差异处理 51 | if col_nums == 23: 52 | values.insert(7, '') 53 | values.insert(8, '') 54 | 55 | if values[20] == '': 56 | values[20] == '0000-00-00 00:00:00' 57 | if values[21] == '': 58 | values[21] = '0000-00-00 00:00:00' 59 | 60 | data.append(tuple(values)) 61 | totals = len(data) 62 | page = False 63 | if totals >= 2000: 64 | insert(data) 65 | page = True 66 | del data 67 | 68 | insert(data) 69 | return True 70 | 71 | 72 | def insert(data): 73 | """ 74 | 将excel表格所有数据一次插入到mysql中 75 | """ 76 | db = MySQLdb.connect(host="localhost", user="root", passwd="", db="fahuo", use_unicode=True, charset="utf8") 77 | c = db.cursor() 78 | 79 | try: 80 | c.executemany( 81 | """INSERT INTO `order` VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", 82 | data) 83 | db.commit() 84 | except Exception as e: 85 | logging.info(e) 86 | db.close() 87 | return False 88 | return True 89 | 90 | 91 | if __name__ == "__main__": 92 | logging.basicConfig(filename='./log.txt', level=logging.DEBUG) 93 | path = './excel' 94 | main(path) 95 | -------------------------------------------------------------------------------- /save_remote_image.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 使用requests保存远程图片(或文件) 4 | import requests 5 | import os 6 | 7 | 8 | def saveRemoteImage(): 9 | imgurl = 'http://www.tantengvip.com/wp-content/uploads/2015/01/cropped-13887362_13887362_1347773771848.jpg' 10 | filename = imgurl.split('/')[-1] 11 | path = './static/'+filename 12 | if not os.path.exists(path): 13 | r = requests.get(imgurl) 14 | with open(path, 'wb') as f: 15 | f.write(r.content) 16 | print('OK') 17 | else: 18 | print('Already exists.') 19 | 20 | """ 21 | 下载大文件这样写: 22 | for chunk in r.iter_content(): 23 | f.write(chunk) 24 | 25 | 如果不使用requests模块: 26 | import urllib 27 | urllib.urlretrieve(url, filename=None, reporthook=None, data=None) 28 | """ 29 | 30 | saveRemoteImage() 31 | -------------------------------------------------------------------------------- /scope.py: -------------------------------------------------------------------------------- 1 | def scope_test(): 2 | def do_local(): 3 | spam = "local spam" 4 | def do_nonlocal(): 5 | nonlocal spam 6 | spam = "nonlocal spam" 7 | def do_global(): 8 | global spam 9 | spam = "global spam" 10 | 11 | spam = "test spam" 12 | do_local() 13 | print("After local assignment:", spam) 14 | do_nonlocal() 15 | print("After nonlocal assignment:", spam) 16 | do_global() 17 | print("After global assignment:", spam) 18 | 19 | scope_test() 20 | print("In global scope:", spam) 21 | 22 | def make_counter(): 23 | count = 0 24 | def counter(): 25 | nonlocal count 26 | count += 1 27 | return count 28 | return counter 29 | 30 | def make_counter_test(): 31 | mc = make_counter() 32 | print(mc()) 33 | print(mc()) 34 | print(mc()) 35 | 36 | make_counter_test() -------------------------------------------------------------------------------- /sendMail.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanteng/learn-python/069ad972f55fe449818a13464cf0847840433916/sendMail.py -------------------------------------------------------------------------------- /singleton.py: -------------------------------------------------------------------------------- 1 | # encoding:utf-8 2 | 3 | # -*- Python单例模式示例 -*- 4 | 5 | class Singleton(object): 6 | def __new__(cls): 7 | if not hasattr(cls, 'instance'): 8 | cls.instance = super(Singleton, cls).__new__(cls) 9 | return cls.instance 10 | 11 | if __name__ == '__main__': 12 | a = Singleton() 13 | b = Singleton() 14 | print(id(a)) 15 | print(id(b)) 16 | -------------------------------------------------------------------------------- /static/cropped-13887362_13887362_1347773771848.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tanteng/learn-python/069ad972f55fe449818a13464cf0847840433916/static/cropped-13887362_13887362_1347773771848.jpg -------------------------------------------------------------------------------- /string_letters.py: -------------------------------------------------------------------------------- 1 | import random, string 2 | 3 | 4 | def rand_str(num, length=7): 5 | f = open('Activation_code.txt', 'w') 6 | for i in range(num): 7 | chars = string.ascii_letters + string.digits 8 | s = [random.choice(chars) for i in range(length)] 9 | f.write('{0}\n'.format(''.join(s))) 10 | f.close() 11 | 12 | 13 | if __name__ == '__main__': 14 | rand_str(200) 15 | -------------------------------------------------------------------------------- /sys_argv.py: -------------------------------------------------------------------------------- 1 | # encoding:utf-8 2 | 3 | # !/usr/bin/env python 4 | 5 | # -*- Python3命令行 -*- 6 | 7 | import optparse 8 | import sys 9 | import webbrowser 10 | 11 | 12 | def process_command_line(argv): 13 | """ 14 | Return a 2-tuple: (settings object, args list). 15 | `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. 16 | """ 17 | if argv is None: 18 | argv = sys.argv[1:] 19 | # initialize the parser object: 20 | parser = optparse.OptionParser( 21 | formatter=optparse.TitledHelpFormatter(width=78), 22 | add_help_option=None) 23 | # define options here: 24 | parser.add_option( # customized description; put --help last 25 | '-h', '--help', action='help', help='Show this help message and exit.' 26 | ) 27 | parser.add_option( 28 | '-u', '--url', action='store', dest = 'link', help='Open a link.' 29 | ) 30 | parser.add_option( 31 | '-v', '--version', action='store_true', help='Show version.' 32 | ) 33 | parser.add_option( 34 | '-q', '--quit', action='store_false',help='Quit' 35 | ) 36 | settings, args = parser.parse_args(argv) 37 | # check number of arguments, verify values, etc.: 38 | if args: 39 | parser.error('program takes no command-line arguments; ' 40 | '"%s" ignored.' % (args,)) 41 | # further process settings & args if necessary 42 | return settings, args 43 | 44 | def main(argv=None): 45 | settings, args = process_command_line(argv) 46 | print(settings) 47 | # application code here, like: 48 | run(settings, args) 49 | return 0 # success 50 | 51 | def run(settings, args): 52 | if settings.link: 53 | webbrowser.open(settings.link, 1) 54 | 55 | if settings.version: 56 | print('VERSION 1.0') 57 | 58 | 59 | 60 | if __name__ == '__main__': 61 | status = main() 62 | sys.exit(status) 63 | 64 | """ 65 | 命令行功能: 66 | 67 | python sys_argv.py -h 68 | 显示帮助信息 69 | 70 | python sys_argv.py -v 71 | 显示版本号 72 | 73 | python sys_argv.py -u www.163.com 74 | 用默认浏览器打开你输入的网址 75 | 76 | action四种参数: 77 | help 显示帮助信息 78 | store 需要参数值 79 | store_true 不需要参数值,默认True 80 | store_false 不需要参数值,默认False 81 | """ -------------------------------------------------------------------------------- /test_mysqlclient.py: -------------------------------------------------------------------------------- 1 | import MySQLdb 2 | 3 | db = MySQLdb.connect(host="localhost", user="root", passwd="", db="demo") 4 | c = db.cursor() 5 | max_price = 5 6 | c.execute("""SELECT * FROM think_node""") 7 | one = c.fetchone() 8 | print(one) 9 | # (49, 'read', '??', 1, '', None, 30, 3, 0, 0) 10 | 11 | all_result = c.fetchall() 12 | print(all_result) 13 | 14 | c.close() # 关闭连接资源 15 | 16 | ''' 17 | ((40, 'Index', '????', 1, '', 1, 1, 2, 0, 0), (39, 'index', '??', 1, '', None, 30, 3, 0, 0), (37, 'resume', '??', 1, '', None, 30, 3, 0, 0), (36, 'forbid', '??', 1, '', None, 30, 3, 0, 0), (3 18 | 5, 'foreverdelete', '??', 1, '', None, 30, 3, 0, 0), (34, 'update', '??', 1, '', None, 30, 3, 0, 0), (33, 'edit', '??', 1, '', None, 30, 3, 0, 0), (32, 'insert', '??', 1, '', None, 30, 3, 0, 19 | 0), (31, 'add', '??', 1, '', None, 30, 3, 0, 0), (30, 'Public', '????', 1, '', 2, 1, 2, 0, 0), (69, 'Form', '????', 1, '', 1, 1, 2, 0, 2), (7, 'User', '????', 1, '', 4, 1, 2, 0, 2), (6, 'Role 20 | ', '????', 1, '', 3, 1, 2, 0, 2), (2, 'Node', '????', 1, '', 2, 1, 2, 0, 2), (1, 'Rbac', 'Rbac????', 1, '', None, 0, 1, 0, 0), (50, 'main', '????', 1, '', None, 40, 3, 0, 0)) 21 | ''' -------------------------------------------------------------------------------- /test_redis.py: -------------------------------------------------------------------------------- 1 | # encoding:utf-8 2 | 3 | import redis 4 | import webbrowser 5 | 6 | 7 | r = redis.StrictRedis(host='localhost', port=6379, db=0) 8 | 9 | r.set('foo', 'bar') 10 | foo = r.get('foo') 11 | 12 | r.sadd('collection','abc') 13 | r.sadd('collection','def') 14 | r.sadd('collection','fhi') 15 | r.sadd('collection','xwy') 16 | 17 | r.zadd('rank',1,'Alibaba') 18 | r.zadd('rank',2,'Tencent') 19 | r.zadd('rank',3,'Baidu') 20 | r.zadd('rank',baidu=3,cc=3,ccc=34) 21 | r.zadd('rank',4,6) 22 | 23 | r.rpush('list','www.tantengvip.com') 24 | r.rpush('list','www.qq.com') 25 | r.rpush('list','www.tencent.com') 26 | 27 | pop = r.lpop('list') 28 | print(pop) 29 | 30 | webbrowser.open('http://www.tantengvip.com',1) 31 | -------------------------------------------------------------------------------- /testmongo.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | from pymongo import MongoClient 4 | import time 5 | import re 6 | import os 7 | import gridfs 8 | import sys 9 | 10 | client = MongoClient('mongodb://192.168.6.212:27017/send_excel') 11 | db = client.js_send_excel 12 | fs = gridfs.GridFS(db) 13 | 14 | files = fs.find() 15 | 16 | time_start = time.clock() 17 | print('总数:', files.count()) 18 | count = 0 19 | 20 | for ffle in files: 21 | filename = ffle.filename 22 | 23 | m = re.match(r'发货订单', filename) 24 | 25 | if m and filename.find('xls') > 0 and not os.path.isfile('./excel/' + filename): 26 | with open('./excel2/' + filename, 'wb') as f1: 27 | f1.write(ffle.read()) 28 | count += 1 29 | 30 | print('执行时间{0}秒'.format(time.clock() - time_start)) 31 | print('本次更新{0}个文档'.format(count)) 32 | -------------------------------------------------------------------------------- /testpillow.py: -------------------------------------------------------------------------------- 1 | from PIL import Image, ImageDraw, ImageFont 2 | 3 | sourceFileName = "fsafa.jpg" 4 | avatar = Image.open(sourceFileName) 5 | drawAvatar = ImageDraw.Draw(avatar) 6 | 7 | xSize, ySize = avatar.size 8 | fontSize = min(xSize, ySize) // 11 9 | 10 | myFont = ImageFont.truetype("/Library/Fonts/OsakaMono.ttf", fontSize) 11 | 12 | drawAvatar.text([0.9 * xSize, 0.1 * ySize - fontSize], "32", fill=(255, 0, 0), font=myFont) 13 | del drawAvatar 14 | 15 | avatar.show() 16 | -------------------------------------------------------------------------------- /testrequests.py: -------------------------------------------------------------------------------- 1 | __author__ = 'tanteng' 2 | 3 | import requests 4 | 5 | def testrequests(): 6 | 7 | url = 'http://www.x.com/index/pyrequests' 8 | 9 | params = { 10 | 'x':'xxxx', 11 | 'y':'yyyy' 12 | } 13 | 14 | re = requests.get(url,params) 15 | 16 | return re 17 | 18 | 19 | if __name__ == '__main__': 20 | re = testrequests() 21 | print(re.text) 22 | 23 | -------------------------------------------------------------------------------- /wechat-ledongli.py: -------------------------------------------------------------------------------- 1 | #coding: utf-8 2 | 3 | #date: 刷微信步数 4 | 5 | #usage: edit steps and ledongli's uid(u need to download this app) .That would be ok .Good luck. ^_^ 6 | 7 | import requests 8 | 9 | import sys 10 | 11 | import json 12 | 13 | import datetime 14 | 15 | import time 16 | 17 | def isnum(value): 18 | 19 | try: 20 | 21 | temp = int(value) 22 | 23 | except Exception as e: 24 | 25 | return False 26 | 27 | else: 28 | 29 | return True 30 | 31 | # like 2015-09-25 00:00:00 converts to unix time stamp 32 | 33 | def formatDate(): 34 | 35 | nowtime = datetime.datetime.now() 36 | 37 | date = time.strftime('%Y-%m-%d') 38 | 39 | strtemp_date = date + ' 00:00:00' 40 | 41 | ledongli_date = time.strptime(strtemp_date, '%Y-%m-%d %H:%M:%S') 42 | 43 | finaldate = time.mktime(ledongli_date) # rusult is 1443456000.0(float type), but still need to format to 1443456000 44 | 45 | finaldate = int(finaldate) 46 | 47 | return finaldate 48 | 49 | def main(steps, uid): 50 | 51 | if not isnum(steps): 52 | 53 | print('param error. steps must be an integer.') 54 | 55 | url = 'http://pl.api.ledongli.cn/xq/io.ashx' 56 | 57 | fake_headers = { 58 | 59 | 'User-Agent' : 'le dong li/5.4 (iPhone; iOS 9.1; Scale/2.00)', 60 | 61 | 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8', 62 | 63 | 'Accept-Encoding': 'gzip' 64 | 65 | } 66 | 67 | keycontentjson = [ 68 | 69 | { 70 | 71 | "date": formatDate(), 72 | "calories": 0, 73 | "activeValue": 108, 74 | "steps": steps, 75 | "pm2d5": 0, 76 | "duration": 0, 77 | "distance": 0, 78 | "report": "[]" 79 | 80 | } 81 | 82 | ] 83 | 84 | # key is a str type 85 | 86 | # key must be a json data convert to string 87 | 88 | key = json.dumps(keycontentjson) 89 | 90 | param = { 91 | 92 | 'action': 'profile', 93 | 94 | 'pc': '29e39ed274ea8e7a50f8a83abf1239faca843022', 95 | 96 | 'cmd': 'updatedaily', 97 | 98 | 'uid': uid, 99 | 100 | 'list': key, 101 | 'v' : '5.4%20ios', 102 | 'vc' : '540%20ios' 103 | } 104 | 105 | r = requests.post(url, data = param, headers = fake_headers) 106 | 107 | print(r.text) 108 | 109 | print('装逼成功') 110 | 111 | if __name__ == '__main__': 112 | 113 | steps = 199999 114 | 115 | uid = '1111111' 116 | 117 | main(steps, uid) -------------------------------------------------------------------------------- /window.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | root = Tk() 4 | frame = Frame(root) 5 | frame.pack() 6 | 7 | var = StringVar() 8 | label = Label( root, textvariable=var, relief=RAISED ) 9 | 10 | var.set("Hey!? How are you doing?") 11 | label.pack(side = TOP) 12 | 13 | bottomframe = Frame(root) 14 | bottomframe.pack( side = BOTTOM ) 15 | 16 | redbutton = Button(frame, text="Red", fg="red") 17 | redbutton.pack( side = LEFT) 18 | 19 | greenbutton = Button(frame, text="Brown", fg="brown") 20 | greenbutton.pack( side = LEFT ) 21 | 22 | bluebutton = Button(frame, text="Blue", fg="blue") 23 | bluebutton.pack( side = LEFT ) 24 | 25 | blackbutton = Button(bottomframe, text="Black", fg="black") 26 | blackbutton.pack( side = BOTTOM) 27 | 28 | root.mainloop() -------------------------------------------------------------------------------- /yun.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | import urllib.request 3 | import re 4 | import os 5 | import sys 6 | 7 | def getHtml(url): 8 | page = urllib.request.urlopen(url) 9 | html = page.read() 10 | return html 11 | 12 | 13 | def getVideo(html): 14 | reg = r'hurl=(.+?\.jpg)' 15 | imgre = re.compile(reg) 16 | imglist = re.findall(imgre,html) 17 | return imglist 18 | 19 | for num in range(28000,1000000): 20 | print (num) 21 | html = getHtml("http://music.163.com/mv?id=%s"%num) 22 | html = html.decode('utf-8') 23 | parsed = getVideo(html) 24 | print(parsed) 25 | if len(parsed)==0: 26 | continue 27 | vedioUrls = parsed[0].split("&") 28 | 29 | artist = vedioUrls[4].split("=")[1].strip() 30 | song = vedioUrls[3].split("=")[1].strip() 31 | if len(vedioUrls[0])==0: 32 | continue 33 | filename = '%s/%s.mp4' %(artist,song) 34 | if "/" in song: 35 | continue 36 | 37 | if os.path.exists(filename): 38 | print ('the MV file exists.%s'%num) 39 | else: 40 | print ('the MV is downloding.%s'%num) 41 | if os.path.exists(artist): 42 | print ("") 43 | else: 44 | os.makedirs(artist) 45 | urllib.request.urlretrieve(vedioUrls[0],filename) --------------------------------------------------------------------------------