python 琐碎记录
1、inspect.getargspect(func)
默认返回值:
A tuple of four things is returned: (args, varargs, keywords, defaults).
args:普通参数
varargs:*args(序列参数)
keywords:**args(关键字参数)
defaults:args参数默认值
from inspect import getargspec def func(a=1,b=3,*c,**d): pass if __name__ == "__main__": print getargspec(func) args, varargs, keywords, defaults = getargspec(func) print args, varargs, keywords, defaults >>ArgSpec(args=['a', 'b'], varargs='c', keywords='d', defaults=(1, 3)) >>['a', 'b'], c,d,(1,3)
2、string的format方法
将string中的{}元素用format中的参数替换
1 print 'the sum of 1 and 2 is {0}'.format(1+2) 2 3 the sum of 1 and 2 is 3 4 5 args = '{arg1}_{arg2}' 6 result = lambda x:args.format(**x) 7 8 pirnt result({'arg1':12, 'arg2:13'}) 9 12_13
3、 functools的partial函数
partial(func[,*arg][.**keyword])
将func的参数附上固定的值
from functools import partial if __name__ == "__main__": print int("10110") ##10110 basetwo = partial(int, base=2) print basetwo("10110") ##22
1 from functools import partial 2 3 def convert_str_to_int(data, base): 4 if base == 2: 5 return int(date, 2) 6 elif base == 10: 7 return int(data) 8 else: 9 return False 10 11 if __name__ == "__main__": 12 print convert_str_to_int("10110", 2) ##22 13 basetwo = partial(convert_str_to_int, base=2) 14 print basetwo("10110") ##22
4、collections的defaultdict方法。
文档
class collections.defaultdict([default_factory[, ...]])
-
Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.
The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.
简单的说就是扩充了内置类型dict的方法,可为其val指定特殊的类型。
1 from collections import defaultdict 2 3 qrs = [{'type': 'a', 'data': 'hello'}, 4 {'type': 'b', 'data': 'hello1'}, 5 {'type': 'b', 'data': 'hello2'}, 6 {'type': 'b', 'data': 'hello3'}, 7 {'type': 'a', 'data': 'hello4'}, 8 {'type': 'a', 'data': 'hello5'}, 9 {'type': 'b', 'data': 'hello6'}, 10 {'type': 'b', 'data': 'hello7'}, 11 ] 12 13 14 15 if __name__ == "__main__": 16 mydict = defaultdict(list) 17 print mydict 18 [mydict[item['type']].append(item['data']) for item in qrs] 19 print mydict 20 result = [{'type': key, 'data': val } for key, val in mydict.items()] 21 print result
输出结果:
defaultdict(<type 'list'>, {})
defaultdict(<type 'list'>, {'a': ['hello', 'hello4', 'hello5'], 'b': ['hello1', 'hello2', 'hello3', 'hello6', 'hello7']})
[{'data': ['hello', 'hello4', 'hello5'], 'type': 'a'}, {'data': ['hello1', 'hello2', 'hello3', 'hello6', 'hello7'], 'type': 'b'}]
5、string的Template
1 from string import Template 2 s = Template('$x, wonderful, $x') 3 y = s.substitute(x='today') 4 print y 5 'today, wonderful, today' 6 print s 7 <string.Template object at 0x01321990>
1 s = Template('today, ${x}ful') 2 print s.substitute(x='wonder') 3 'today, wonderful'
1 s = Template('today,$$,is $x') 2 print s.substitute(x='wonderful') 3 'today,$,is wonderful'
1 s = Template('a $thing must never $action') 2 d = {} 3 d['thing'] = 'gentleman' 4 d['action'] = 'show his socks' 5 print s.substitute(d) 6 'a gentleman must never show his socks'
6、string的maketrans
1 from string import maketrans 2 table = maketrans('abcd', 'efgh') 3 print len(table) 4 256 5 print table[97:123] 6 'efghefghijklmnopqrstuvwxyz' 7 print maketrans('', '')[97:123] 8 'abcdefghijklmnopqrstuvwxyz'
1 print 'abcdfeeaaff'.translate(table) 2 'efghfeeeeff' 3 print 'abdsc eidis aaaa'.translate(table, ' ') 4 'efhsgeihiseeee' 5 6 第二个参数代表删除的字符
7、string的格式化
1 print 'nice,%s'%'today' 2 'nice,today' 3 print '%s,%s'%('nice', 'today') 4 'nice,today' 5 print '%s,%d'%('ncie', 666) 6 'ncie,666' 7 print 'nice, %(date)s'%{'date':'today'} 8 'nice, today' 9 print 'nice, %(date)d'%{'date':2012} 10 'nice, 2012'
8、copy的deepcopy
1 from copy import deepcopy 2 d={} 3 d['date']=['yes', 'tod', 'tor'] 4 c = d.copy() 5 dc = deepcopy(d) 6 print c,dc 7 {'date': ['yes', 'tod', 'tor']} {'date': ['yes', 'tod', 'tor']} 8 d['date'].remove('yes') 9 print d,'\n', c,'\n', dc 10 {'date': ['tod', 'tor']} 11 {'date': ['tod', 'tor']} 12 {'date': ['yes', 'tod', 'tor']}
1、tgfile.readlines()是全部读入内存,采用生成器for line in tgfile更优
2、if data[0] not in dicts.keys()效率太低,这和if data[0] not in dicts是一回事,后者效率高很多。
dicts.keys() 得到的是一个 list。
in 算符在 list 上的时间复杂度是 O(n)
而在 dict 上是基于 hash 的,时间复杂度是 O(1)。
在大数据量的时候它们的速度能差上几个数量级。
3、jinja2 渲染变量 {{ 2.34|int()}}, {{2 | float()}}
from jinja2 import Template
items = [1,2,3,4,5]
template = Template('hello {{items | length()}}')
result = template.render(items=items)
print result
4、unicode 和字节流
>>> a = "和"
len(a) = 3
>>> a
'\xe5\x92\x8c'
>>> b = u"和"
len(b) = 1
>>> b
u'\u548c'
>>> i.encode('utf-8')
'\xe5\x92\x8c'
11.5
* python subprocess几个方法的区别:Popen,call。主要是父进程是否等待子进程执行完毕。
* find 命令的一个用法:find . -name "*hello.c" -exec rm {} \;
* gunicorn debug 模式: gunicorn myapp:app -b localhost:prot --debug --log-level debug
* date:
date +%Y%m%d
date -d "7 days ago" +%Y%m%d
* md5sum filename > filename.md5
md5sum -c filename.md5
* bash控制流:
if [ variable != "XXX" ];then
xxxxxxxx
fi
11.6
* mysql 重复查询 select * from tablename where column in (select column where tablename group by column count(column) > 1);
* mysql 联表查询 select a.id, b.id from tablename_a as a, tablename_b as b where a.column = b.column;
* oauth 流程 http://www.360doc.com/content/11/0513/18/1542811_116513607.shtml
* datetime timedelta
* sudo sudoedit /etc/sudoer 和 sudo vi /etc/sudoers的区别
* mysql导入数据
shell>> mysqladmin -h host -u username -p create dbname
shell>> mysql -h host -u username -p dbname < table.sql
11.7
* alter table `tablename` drop column Gatewayid
*AUTO_INCREMENT 的开始值是 1,不是0
11.13
* python 2.2X int(a) 当a超过32位时,会自动转为long型
* python字典作为参数:
a = {"a": 1, "b": 2 , "c": 3}
def temp(a,b,c):
print a,b,c
temp(**a) ##1,2,3
* 给文件加可执行权限:
chmod a+x temp.py
之后就可以直接执行了:/http://www.cnblogs.com/temp.py
11.14
* python参数
def temp(*args, **kwargs): print args, kwargs print temp(1,2,3,a=4,b=5) (1, 2, 3) {'a': 4, 'b': 5}
* class Temp(object):
类的属性
t._a
t.__dict__
t.__a
Python中并没有真正意义上的“私有”,类的属性的的可见性取决于属性的名字(这里的属性包括了函数)。例如,以单下划线开头的属性(例如_spam),应被当成API中非公有的部分(但是注意,它们仍然可以被访问),一般是具体实现细节的部分。单下划线常用来实现模块级私有化,当我们使用“from mymodule import *”来加载模块的时候,不会加载以单下划线开头的模块属性。
而以双下划线开头并最多以一个下划线结尾的属性(例如___spam),将会被替换成_classname__spam这样的形式,其中classname是当前类的类名。知道了这点之后,
* __slots__
用于新式类中,可以限制类的实例可以访问的合法属性集。
* __getstate__
__setstate__
http://blog.csdn.net/jiangnanandi/article/details/3032421
http://stackoverflow.com/questions/1939058/simple-example-about-setstate-and-getstate
* (3 == 3) if 2 else 3 ##True
(3 == 3) if 0 else 3 ##False
if XX 为真,执行(),否认else 3
11.16
* from collections import OrderDict
http://www.cnblogs.com/abeen/archive/2011/10/10/2205640.html
11.19
* nginx rewrite post请求会被变为get请求
*mysql int(3) int(4) 没有区别,
varchar(20) varchar(30) ,有区别,超过20.或者30的会被截断。
11.24
新式类和旧式类
class Base:
pass
class Base(object):
pass
二者差别,子类查询父类方法不同,前者为深度优先,后者为广度优先。
12.20
1、edquota -p source_username target_username
功能说明:编辑用户或群组的quota。
语 法:edquota [-p <源用户名称>][-ug][用户或群组名称...] 或 edquota [-ug] -t
补充说明:edquota预设会使用vi来编辑使用者或群组的quota设置。
参 数:
-u 设置用户的quota,这是预设的参数。
-g 设置群组的quota。
-p<源用户名称> 将源用户的quota设置套用至其他用户或群组。
-t 设置宽限期限。
2、/etc/init.d/nginx reload
/etc/init.d/nginx restart
区别
3、useradd -d /data/octopress/username -m username -s /usr/bin/rssh
资料:http://www.cppblog.com/prayer/archive/2009/08/13/93234.html
rssh : scp, rsync
userdel -r username
4、sudo不需要密码
sudo visudo -f /etc/sudoers
stdyun ALL=(ALL:ALL) ALL 增加sudo权限
stdyun ALL=(ALL) NOPASSWD: ALL sudo不用密码
5、 open
readline(size)
12.22
1、查看linux load
uptime
w
2、
1.3
删除文件
import os
os.remove(filename)
复制文件:
import shutil
shutil.copyfile(src_filename, tar_filename)
shutil.copy(src_filename, tar_filename)
内省:
import inspect
inspect.isfunction(object)
inspect.ismethod(object)
re
match对象方法
u = re.search(r"[0-9]", "ddds2223fff4444")
u.group()
u.groups()
u.span()
In [230]: r = re.compile(r"(blue|white|red)")
In [231]: r.sub("black", "blue, white and red is color")
Out[231]: 'black, black and black is color'
In [232]: r.sub("black", "blue, white and red is color", 1)
Out[232]: 'black, white and red is color'
In [233]: r = re.compile(r"(blue|white|red)")
In [234]: r.subn("black", "blue, white and red is color")
Out[234]: ('black, black and black is color', 3)
In [235]: r.subn("black", "blue, white and red is color", 1)
Out[235]: ('black, white and red is color', 1)
浙公网安备 33010602011771号