python
文章平均质量分 50
SnowRomance
这个作者很懒,什么都没留下…
展开
-
windows 进程监控
# 定期监视某进程是否存在,不存在则执行 import os,time def __Is_Process_Running(imagename): ''' 功能:检查进程是否存在 返回:返回有多少个这进程名的程序在运行,返回0则程序不在运行 ''' p = os.pope转载 2016-05-23 10:27:07 · 637 阅读 · 0 评论 -
序列化
1.pickleimport pickled = dict(name='Bob', age=20, score=88)pickle.dumps(d)#with open('dump.txt', 'wb') as f:# pickle.dump(d, f)with open('xxx', 'rb') as f: pickle.load(f)print(d原创 2016-05-27 17:20:13 · 273 阅读 · 0 评论 -
文件和目录
os 模块:import osos.name #操作系统的类型os.uname() # 操作系统完成信息os.environ # 操作系统环境变量os.environ.get('PATH')os.path.abspath('.') # 查看当前目录的绝对路径# 在某个目录下创建一个新目录,首先把新的完整的目录路径表示出来os.path.join('/Users/m原创 2016-05-27 17:19:44 · 235 阅读 · 0 评论 -
StringIO 跟 BytesIO
StringIO:from io import StringIOf = StringIO()f.write('hello')print(f.getvalue())或者from io import StringIOf = StringIO('Hello!\nHi!\nGoodbye!')while True: s = f.readline()原创 2016-05-27 17:19:13 · 281 阅读 · 0 评论 -
文件读写
1.普通文件如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便:with open('/path/to/file', 'r') as f: for line in f.readlines(): print(line.strip())原创 2016-05-27 17:18:46 · 258 阅读 · 0 评论 -
调试
1.print()2.assertassert n!=0, 'n is zeto!'assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。3.loggingimport logginglogging.basicConfig(level=logging.INFO)n = int('0')logging.info原创 2016-05-27 17:18:21 · 255 阅读 · 0 评论 -
元类
type()class Hello(object): def hello(self, name='world'): print('Hello, %s.' % name)h = Hello()h.hello()print(type(Hello))type()函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是t原创 2016-05-27 17:17:52 · 209 阅读 · 0 评论 -
枚举类
1.使用 Enum 类from enum import EnumMonth = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))2.使用 Enum 派生自定义类from enum import Enum, unique原创 2016-05-27 17:16:35 · 238 阅读 · 0 评论 -
定制类
1.__str__只需要定义好__str__()方法,返回一个好看的字符串就可以了:>>> class Student(object):... def __init__(self, name):... self.name = name... def __str__(self):... return 'Student object (原创 2016-05-27 17:16:09 · 241 阅读 · 0 评论 -
多继承
MixIn在设计类的继承关系时,通常,主线都是单一继承下来的,例如,Ostrich继承自Bird。但是,如果需要“混入”额外的功能,通过多重继承就可以实现,比如,让Ostrich除了继承自Bird外,再同时继承Runnable。这种设计通常称之为MixIn。为了更好地看出继承关系,我们把Runnable和Flyable改为RunnableMixIn和FlyableMixIn。类似的,你还可转载 2016-05-27 17:15:39 · 256 阅读 · 0 评论 -
property 定义 getter 跟 setter 方法
class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): self._birth = value @property def age(self):原创 2016-05-27 17:15:16 · 554 阅读 · 0 评论 -
使用 __slots__
动态添加类的属性跟方法:属性:class Student(object): passs = Student()s.name = 'Michael'print(s.name)方法:def set_age(self, age): self.age = agefrom types import MethodTypes.set原创 2016-05-27 17:14:54 · 289 阅读 · 0 评论 -
类属性与实例属性
给实例绑定属性的方法是通过实例变量,或者通过self变量:class Student(object):def __init__(self, name): self.name = names = Student('Bob')s.score = 90但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student类所有:原创 2016-05-27 17:14:14 · 359 阅读 · 0 评论 -
作用域
在一个模块中,我们可能会定义很多函数和变量,但有的函数和变量我们希望给别人使用,有的函数和变量我们希望仅仅在模块内部使用。在Python中,是通过_前缀来实现的。正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等;类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量,转载 2016-05-27 17:13:38 · 208 阅读 · 0 评论 -
偏函数
创建偏函数时,实际上可以接收函数对象、*args和**kw这3个参数1.int2 = functools.partial(int, base = 2)int2('10010')相当于:kw = {'base' : 2}int('10010', **kw)2.max2 = functools.partial(max, 10)max原创 2016-05-27 17:13:11 · 222 阅读 · 0 评论 -
装饰函数
import functoolsdef log(func): @functools.wraps(func) def wrapper(*args, **kw): print('call %s():' % func.__name__) print('begin call') func(*args, **kw) prin原创 2016-05-27 17:12:15 · 385 阅读 · 0 评论 -
求素数
def _odd_iter(): n = 1 while True: n += 2 yield ndef _non_divisable(n): return lambda x: x % n > 0def prime(): yield 2 it = _odd_iter() while True:转载 2016-05-27 17:11:54 · 284 阅读 · 0 评论 -
多进程
1.fork():import os pid = os.fork()if pid == 0: print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))else: print('I (%s) just created a child process原创 2016-05-27 17:20:39 · 341 阅读 · 0 评论 -
操作 excel 读 xlrd
安装相关模块 pip install xlrdimport xlrdimport datetime# 打开文件wb = xlrd.open_workbook('test.xlsx')# 获取表table = wb.sheets()[0]table2 = wb.sheet_by_index(1)table3 = wb.sheet_by_name(u'Sheet3')原创 2016-05-16 09:40:26 · 494 阅读 · 0 评论 -
断点调试
import pdb; pdb.set_trace() # 运行到这语句,会出现断点 输入命令: 命令的详细帮助: h 查看代码上下文, l(小写L) 监视变量: p 变量名 单步执行: n 加入断点: b 行号 跳出断点: c 执行到函数返回前: r原创 2016-05-23 10:26:38 · 238 阅读 · 0 评论 -
防止 print 自动换行
print(line, end=' ')以 end 结尾输出,而不是 \n原创 2016-05-23 10:26:09 · 636 阅读 · 0 评论 -
python下编译py成pyc和pyo
其实很简单,用python -m py_compile file.pypython -m py_compile /root/src/{file1,file2}.py编译成pyc文件。也可以写份脚本来做这事:Code:import py_compile py_compile.compile('path') //path是包括.py文件名的路径转载 2016-05-23 10:23:43 · 13019 阅读 · 0 评论 -
正则表达式
正则表达式 正则表达式有强大并且标准化的方法来处理字符串查找、替换以及用复杂模式来解析文本。 正则表达式的语法比程序代码更紧凑,格式更严格,比用组合调用字符串处理函数的方法更具有可读性。 还可以在正则表达式中嵌入注释信息,这样就可以使它有自文档化的功能。 匹配符: ^ 匹配字符串开始位置。在多行字符串模式匹配每一行的开头原创 2016-05-23 10:23:25 · 1052 阅读 · 0 评论 -
yield 函数
1.调用 yield 注意: generator 中 的 next() 方法 在 python 3.x 中改成了 generator.__next__()def gen(): print('enter') yield 1 print('next') yield 2 p原创 2016-05-23 10:23:08 · 308 阅读 · 0 评论 -
lambda 格式
lambda 语句被用来创建新的函数对象,并且在运行时返回它们一般的函数定义def add(a,b): return a+blambda 定义:add = lambda a,b: a+b调用函数的区别:一般的函数:add(1,2)lambda 函数:add(1, 2)其中 lambda 函数可以进行 匿名函数原创 2016-05-23 10:22:44 · 794 阅读 · 0 评论 -
list sort 自定义 key 方法
1. sort 自定义 key 排序L = [('a', 1), ('b', 0), ('c', 4), ('d', 3)]L.sort(key=lambda d: -d[1])print(L)原创 2016-05-23 10:21:20 · 653 阅读 · 0 评论 -
random
#python randomimport randomdef get_random(): '''get a random number. return Random float x, 0.0 return random.random()def get_uniform(a, b): '''Return a random f转载 2016-05-06 16:26:30 · 177 阅读 · 0 评论 -
Counter
#python counter objectfrom collections import *import osdef get_counter(): '''get the Counter object''' return Counter()def str_to_list(s): ''' a string covert转载 2016-05-06 16:23:58 · 406 阅读 · 0 评论 -
tkinter
#python tkinter modulefrom tkinter import *def get_main_window(): '''create main window.''' return Tk()def set_main_window_size(root): '''set size of the main window.'转载 2016-05-06 16:23:43 · 231 阅读 · 0 评论 -
count()函数
python中的count()函数,从字面上可以知道,他具有统计功能功能:读取一个文件'c:\\test.txt',统计出该文件中出现字符'a'的次数#python openimport osnumber = 0def get_number_of_char(filePath, c): ''' from path, the system转载 2016-05-06 16:23:22 · 700 阅读 · 0 评论 -
python3.5连接 mysql
原命令:pip install mysql-connector-python --allow-external mysql-connector-python命令遇到错误 Could not find a version that satisfies the requirement mysql-connector-python (from versions: )No matchin原创 2016-05-05 09:41:42 · 714 阅读 · 0 评论 -
calendar
#python中的calendarimport calendar#返回指定年的某月def get_month(year, month): return calendar.month(year, month)#返回指定年的日历def get_calendar(year): return calendar.calendar(year)转载 2016-05-05 09:41:19 · 225 阅读 · 0 评论 -
textwrap提供了一些方法
wrap(text, width = 70, **kwargs):这个函数可以把一个字符串拆分成一个序列fill(text, width=70, **kwargs) :该方法可以根据指定的长度,进行拆分字符串,然后逐行显示dedent()方法->文本进行不缩进显示,相应的indent()方法 -> 进行缩进显示原创 2016-05-05 09:40:52 · 331 阅读 · 0 评论 -
time
#datetimeimport datetime#当前日期now = datetime.datetime.now()print(now.strftime('%Y-%m-%d %H:%M:%S'))print(now.strftime('%Y-%m-%d'))#string convert to datetimetime_str = '2013-0转载 2016-05-05 09:40:12 · 218 阅读 · 0 评论 -
操作 excel 写 xlwt
安装相关模块 pip install xlwtimport xlwt# 简单的写入# write_merge(x, x + m, y, w + n, string, sytle)# x表示行,y表示列,m表示跨行个数,n表示跨列个数,string表示要写入的单元格内容,style表示单元格样式。其中,x,y,w,h,都是以0开始计算的。# 这个和xlrd中的读合并单元格原创 2016-05-16 09:40:43 · 793 阅读 · 0 评论 -
str.format()
#使用str.format()函数#使用'{}'占位符print('I\'m {},{}'.format('Hongten','Welcome to my space!'))print('#' * 40)#也可以使用'{0}','{1}'形式的占位符print('{0},I\'m {1},my E-mail is {2}'.format('Hello',转载 2016-05-04 11:32:13 · 242 阅读 · 0 评论 -
迭代
列表迭代:L = ['Adam', 'Lisa', 'Bart', 'Paul']R = [1, 2, 3, 4]for index, name in zip(R,L): print index, '-', namedict value迭代:d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }原创 2016-05-04 11:31:55 · 250 阅读 · 0 评论 -
python 递归实现 汉诺塔
def move(n, a, b, c): if n==1: print a, '-->',c return move(n-1,a,c,b) print a, '-->', c move(n-1,b,a,c)move(4, 'A', 'B', 'C')原创 2016-05-04 11:31:35 · 499 阅读 · 0 评论 -
安装 Mysql_Python
1.下载 mysql-pythonhttps://pypi.python.org/pypi/MySQL-python/1.2.52.解压安装unzip MySQL-python-1.2.5.zipcd MySQL-python-1.2.5python setup.py buildpython setup.py install报错1:Impor原创 2016-05-03 09:55:29 · 262 阅读 · 0 评论 -
smtp 邮件发送
#!/usr/bin/python# -*- coding: UTF-8 -*-import smtplibfrom email.mime.text import MIMEText from email.mime.multipart import MIMEMultipartsender='liuyangjun@zjcap.cn'receivers=['li原创 2016-05-03 09:54:23 · 904 阅读 · 0 评论