python小知识_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 "", line 1, in ?

File "/usr/lib/python2.3/encodings/gb2312.py", line 21, in encode

if c < uu0080:

UnicodeDecodeError: ascii codec cant decode byte 0xe4 in position 0: ordinal not in range(128)

>>> unicode(a,utf-8)

uu4e2du56fd

>>> b = unicode(a,utf-8)

>>> print b

中国

>>> c = b.encode(gb2312)

>>> c

xd6xd0xb9xfa

>>> 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 "", 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[self.index]

...

>>> 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

>>> 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=[c for c in abcdefg]

>>> a

[a, b, c, d, e, f, g]

>>>

按if条件拆分序列

>>> a=[c for c in 123456 if int(c)<3]      如果if的条件为真,则执行for循环

>>> a

[1, 2]

>>> a=[c for c in 123456 if int(c)>3]      如果if的条件为假,则不执行for循环

>>> a

[4, 5, 6]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值