jane27 发表于 2017-5-2 11:47:03

Python的一些小技巧小知识


Chapter12.HOW-TO








  本章内容记录Python的一些小技巧小知识。来源是网上摘录或自己学习所得。


[*]  如何判断操作系统类型

import sys
print sys.platform
print sys.version
[*]  显示和修改python的Module搜索路径

>>> import sys
>>> print sys.path
['', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2',
'/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages',
'/usr/lib/python2.3/site-packages']
>>> sys.path.append('/usr/lib/mypath')
>>> print sys.path
['', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2',
'/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages',
'/usr/lib/python2.3/site-packages', '/usr/lib/mypath']
[*]  把列表转换成字符串

>>> t=['a','b','c']
>>> print t
['a', 'b', 'c']
>>> import string
>>> print string.join(t)
a b c
[*]  运行系统程序

>>>import os
>>>os.system('ls')            #用os.system()可执行系统命令
>>>exec "os.system('ls')"   #用exec可执行字符串中的命令,两个命令的效果一样。

  以上两个命令的输出都是直接显示在屏幕上,不能保存到变量中,如果我们要把输出保存起来,可用os.pope/ n()函数。

>>>cmd = '/usr/bin/mkntpwd %s' % password
>>>handler = os.popen(cmd,'r')
>>>passwordString=handler.read()   #passwordString为mkntpwd程序的输出结果

  使用commands模块也可以获取程序的输出,它包含一些基于os.popen()的封装函数,使我们能更方便地获取运行系统命令和获取命令的输出,但该模块只在Unix系统下有效,不能用于Windows平台。

>>> import commands
>>> status,output = commands.getstatusoutput('ls -l')
>>> print output
总计 96564
-rw-r--r--1 root   root         4459 2005-12-01 10:23 2005.sxw
-rw-r--r--1 root   root      27511 2006-04-12 16:54 20060412_user.ods
-rw-r--r--1 root   root       202258 2006-01-06 16:48 2006风景-1月.jpg
...
>>> print status
0

  在Python2.4中引入一个新的模块叫subprocess,用于取代os.system、os.spawn*、os.popen*、popen2.*、commands.*。

[*]  编码转换

#!/usr/bin/python
#-*-coding:utf-8 -*-
a=u"测试"
b=a.encode('gb2312')
print a
print b

>>> a = '中国'
>>> a.encode('gb2312')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.3/encodings/gb2312.py", line 21, in encode
if c < u'/u0080':
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> unicode(a,'utf-8')
u'/u4e2d/u56fd'
>>> b = unicode(a,'utf-8')
>>> print b
中国
>>> c = b.encode('gb2312')
>>> c
'/xd6/xd0/xb9/xfa'
>>> print c                              # c是gb2312字符集的‘中国’,在我的utf-8系统中显示乱码是正常的。
?
>>>
PS:我的shell环境是utf-8。
[*]  交换两个变量

>>> a,b = 1,2
>>> a,b
(1, 2)
>>> a,b = b,a
>>> a,b
(2, 1)
>>> a
2
>>> b
1
[*]  测试数据类型

>>> a=123
>>> b='test'
>>> a
123
>>> b
'test'
>>> isinstance(a,int)
True
>>> isinstance(a,str)
False
>>> isinstance(b,int)
False
>>> isinstance(b,str)
True
[*]  用in判断是否包含子字符串

>>> a='this is my test'
>>> 'is' in a
True
>>> 'mm' in a
False
[*]  __iter__迭代器

>>> a = "iterator"
>>> t = iter(a)
>>> t.next()
'i'
>>> t.next()
't'
>>> t.next()
'e'
>>> t.next()
'r'
>>> t.next()
'a'
>>> t.next()
't'
>>> t.next()
'o'
>>> t.next()
'r'
>>> t.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration

  自已写一个迭代器类

>>> class reverse:
...   def __init__(self,data):
...             self.data=data
...             self.index=len(data)
...   def __iter__(self):
...             return self
...   def next(self):
...             if self.index == 0:
...                     raise StopIteration
...             self.index = self.index - 1
...             return self.data
...
>>> for char in reverse('iterator'):
...   print char
...
r
o
t
a
r
e
t
i
>>>
[*]  通过getattr可以得到一个在运行时才知道具体函数名的对象的引用,能增强我们程序的灵活性。

>>> li=['a','b']
>>> getattr(li,'append')
>>> getattr(li,'append')('c')          #相当于li.append('c')
>>> li
['a', 'b', 'c']
>>> handler=getattr(li,'append',None)
>>> handler
<built-in method append of list object at 0xb7d4a52c>
>>> handler('cc')                      #相当于li.append('cc')
>>> li
['a','b','c','cc']
>>>result = handler('bb')
>>>li
['a','b','c','cc','bb']
>>>print result
None

  编程示例:

import statsout
def output(data, format="text"):                              
output_function = getattr(statsout, "output_%s" % format)
return output_function(data)                              

  以上代码表示,output函数接收一个data参数和format参数,根据format参数的值,从statsout模块中取出output_text函数运行,data参数通过output_function(data)传递给了statsout模块中的output_text函数。format取不同值可从statsout模块中取出不同的函数运行(output_xxxx)。也就是说我们要运行的函数是在程序运行后才确定的。这样我们可把不同的函数以output_xxx形式命名放在statout模块中,通过以上程序可动态调用各种函数。

[*]  hasattr用于确定一个对象是否具有某个属性。

语法:
hasattr(object, name) -> bool
判断object中是否有name属性,返回一个布尔值。
[*]  拆分序列

>>> a=
>>> a
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>>

  按if条件拆分序列

>>> a=      如果if的条件为真,则执行for循环
>>> a
['1', '2']
>>> a=      如果if的条件为假,则不执行for循环
>>> a
['4', '5', '6']
[*]  __dict__记录模块或类中所有对象的信息,它以字典{name:object}的形式记录这些信息,如果wikiaction是一个模块,则可以这样显示:

>>>import wikiaction
>>>print wikiaction.__dict__
{'do_test': <function do_test at 0xb7c10534>, 'do_diff': <function do_diff at 0xb7c0ef0c>, 'do_refresh': <fun
ction do_refresh at 0xb7c1025c>, 'do_userform': <function do_userform at 0xb7c103e4>, 'getHandler': <function
getHandler at 0xb7c105a4>, 'do_raw': <function do_raw at 0xb7c10454>, 'do_chart': <function do_chart at 0xb7
c104c4>, 're': <module 're' from '/usr/lib/python2.3/re.pyc'>, 'pysupport': <module 'MoinMoin.util.pysupport'
from '/usr/lib/python2.3/site-packages/MoinMoin/util/pysupport.pyc'>, 'config': <module 'MoinMoin.config' fr
om '/usr/lib/python2.3/site-packages/MoinMoin/config.pyc'>}
[*]  'and'的特殊用法

>>> 'a' and 'b'         #如果两个都为真值,返回最后一个真值
'b'
>>> 'b' and 'a'         #同上
'a'
>>> 'a' and 'b' and 'c' #同上
'c'
>>> '' and 'a'          #如果有假值,则返回假值
''
>>> 'a' and '' and 'c'#同上
''
>>> '' and 0            #如果两个都为假值,返回第一个假值
''
>>> 0 and ''            #同上
0
[*]  'or'的的特殊用法

>>> 'a' or 'b'          #如果有一个为真值,则返回第一个真值
'a'
>>> 'b' or 'a'          #同上
'b'
>>> 'a' or 'b' or ''    #同上
'a'
>>> 0 and '' and {}   #如果所有都是假值,则返回第一个假值
0
>>> {} and '' and {}    #同上
{}
[*]  lambda匿名函数的用法

>>> a=lambda c:c*2
>>> a
<function <lambda> at 0xb7dd710c>
>>> a(2)
4
>>> a(5)
10
[*]  用一条Python命令创建一个Web Server。

debian:~# python -c "from SimpleHTTPServer import test; test()"
如果你的Python版本支持-m参数,也可用以下命令:
debian:~# python -m SimpleHTTPServer
页: [1]
查看完整版本: Python的一些小技巧小知识