[Python]如何快速知道要使用哪些python模块和有哪些功能
1,查看python自带的lib, 例如:http://docs.python.org/3.1/library/
2,如果想看自己的python项目都导入了那些模块,可以用sys.modules输出来看下
>>> import sys
>>> sys.modules
3,以上只列出了当前已经import的module,磁盘上没有import的不会被列出来。之后进入/usr/local/lib/python2.7/ 这里看
4,擅用help()和dir()命令,例如:
help()
modules
5,另外,Python还提供了若干内置的函数,用于在运行时操作指定对象的属性。具体如下:
hasattr(obj, name) #判断obj对象是否具有名为name的属性
setattr(obj, name, value) #设置obj对象的名为name的属性值为value
getattr(obj, name) #获取obj对象的名为name的属性值
delattr(obj, name) #删除obj对象的名为name的属性
6,内置的dir()函数进行反射,从而了解到某个对象分别都包含哪些属性
type()函数获取对象的类型
所有的Python对象,都可以通过内置的id()函数获取该对象的唯一标示。而且当一个对象创建之后,这个唯一标示就会始终保持不变。
7,继承的语法
Python的继承语法,相比C++/Java而言,更加简洁。比如子类Child需要继承父类Parent,代码只需如下:
class Child(Parent) :
如果是多继承,代码大同小异:
class Child(Parent1, Parent2, Parent3) :
如果你想知道某个类有哪些父类(基类),只需要通过 Child.__bases__ 便可知晓。
===========================================================
Graphical interface wxPython http://wxpython.org
Graphical interface pyGtk http://www.pygtk.org
Graphical interface pyQT http://www.riverbankcomputing.co.uk/pyqt/
Graphical interface Pmw http://pmw.sourceforge.net/
Graphical interface Tkinter 3000 http://effbot.org/zone/wck.htm
Graphical interface Tix http://tix.sourceforge.net/
Database MySQLdb http://sourceforge.net/projects/mysql-python
Database PyGreSQL http://www.pygresql.org/
Database Gadfly http://gadfly.sourceforge.net/
Database SQLAlchemy http://www.sqlalchemy.org/
Database psycopg http://www.initd.org/pub/software/psycopg/
Database kinterbasdb http://kinterbasdb.sourceforge.net/
Database cx_Oracle http://www.cxtools.net/default.aspx?nav=downloads
Database pySQLite http://initd.org/tracker/pysqlite
MSN Messenger msnlib http://auriga.wearlab.de/~alb/msnlib/
MSN Messenger pymsn http://telepathy.freedesktop.org/wiki/Pymsn
MSN Messenger msnp http://msnp.sourceforge.net/
Network Twisted http://twistedmatrix.com/
Images PIL http://www.pythonware.com/products/pil/
Images gdmodule http://newcenturycomputers.net/projects/gdmodule.html
Images VideoCapture http://videocapture.sourceforge.net/
Sciences and Maths scipy http://www.scipy.org/
Sciences and Maths NumPy http://numpy.scipy.org/
Sciences and Maths numarray http://www.stsci.edu/resources/software_hardware/numarray
Sciences and Maths matplotlib http://matplotlib.sourceforge.net/
Games Pygame http://www.pygame.org/news.html
Games Pyglet http://www.pyglet.org/
Games PySoy http://www.pysoy.org/
Games pyOpenGL http://pyopengl.sourceforge.net/
Jabber jabberpy http://jabberpy.sourceforge.net/
Web scrape http://zesty.ca/python/scrape.html
Web Beautiful Soup http://crummy.com/software/BeautifulSoup
Web pythonweb http://www.pythonweb.org/
Web mechanize http://wwwsearch.sourceforge.net/mechanize/
Localisation geoname.py http://www.zindep.com/blog-zindep/Geoname-python/
Serial port pySerial http://pyserial.sourceforge.net/
Serial port USPP http://ibarona.googlepages.com/uspp
Parallel Port pyParallel http://pyserial.sourceforge.net/pyparallel.html
USB Port pyUSB http://bleyer.org/pyusb/
Windows ctypes http://starship.python.net/crew/theller/ctypes/
Windows pywin32 http://sourceforge.net/projects/pywin32/
Windows pywinauto http://www.openqa.org/pywinauto/
Windows pyrtf http://pyrtf.sourceforge.net/
Windows wmi http://timgolden.me.uk/python/wmi.html
PDA/GSM/Mobiles pymo http://www.awaretek.com/pymo.html
PDA/GSM/Mobiles pyS60 http://sourceforge.net/projects/pys60
Sound pySoundic http://pysonic.sourceforge.net/
Sound pyMedia http://pymedia.org/
Sound FMOD http://www.fmod.org/
Sound pyMIDI http://www.cs.unc.edu/Research/assist/developer.shtml
GMail libgmail http://libgmail.sourceforge.net/
Google pyGoogle http://pygoogle.sourceforge.net/
Expect pExpect http://pexpect.sourceforge.net/
WordNet pyWordNet http://osteele.com/projects/pywordnet/
Command line cmd http://blog.doughellmann.com/2008/05/pymotw-cmd.html
Compiler backend llvm-py http://mdevan.nfshost.com/llvm-py/
3D VPython http://vpython.org
这个模块包含Python中使用的内建函数,一般不用手动导入这个模块,Python会帮你做好一切。
下面将一一介绍这个模块所常有的函数。
1. 加载和重载模块:
import语句是用来导入外部模块的(也可使用from -- import)其实import是靠调用内建函数__import__来工作的。
例如 import spam 其实就是相当于执行下面一行代码
spam = __import__( 'spam' , globals() , locals() , [] , 0)
import spam.ham相当于执行下面一行代码
spam = __import__( 'spam.ham' , globals() , locals() , [] , 0)
from spam.ham import eggs , sausage as saus 相当于执行下面一行代码
_temp = __import__( 'spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
2. dir()
返回由给定模块,类,实例或其他类型的所有成员组成的列表。
[python] view plaincopy
<span style="font-size:14px;">import sys
def dump(value):
print(value,'=>',dir(value))
dump([]) #list
dump({}) #dictionary
dump('string')
dump(len) #function
dump(sys) #module</span>
3. vars()
返回的是包含每个成员当前值的字典,如果你使用不带参数的vars,它将返回当前局部名称空间的可见元素(同locals()函数)
[python] view plaincopy
<span style="font-size:14px;">book = 'library2'
pages = 250
scripts = 350
print('the %(book)s book contains more than %(scripts)s scripts'%vars())</span>
结果是:the library2 book contains more than 350 scripts
4. type()
允许你检查一个变量的类型,这个函数会返回一个type descriptor(类型描述符),它对于python解释器提供的每个类型都是不同的。
[python] view plaincopy
<span style="font-size:14px;">def dump(value):
print(type(value),value)
dump(1)
dump(1.0)
dump('one')</span>
结果:
<class 'int'> 1
<class 'float'> 1.0
<class 'str'> one
5. callable()
可以检查一个对象是否是可调用的,对于函数,方法,lambda函式,类,以及实现了__call__方法的类实例,它都返回True
[python] view plaincopy
<span style="font-size:14px;">def dump(function):
if callable(function):
print(function,'is callable')
else:
print(function,'is not callable')
class A:
def method(self,value):
return value
class B:
def __call__(self,value):
return value
a = A()
b = B()
dump(0)
dump('string')
dump(callable)
dump(dump)
dump(A)
dump(B)
dump(a)
dump(b)</span>
结果:
0 is not callable
string is not callable
<built-in function callable> is callable
<function dump at 0x00C4FED0> is callable
<class '__main__.A'> is callable
<class '__main__.B'> is callable
<__main__.A object at 0x00C6C1F0> is not callable
<__main__.B object at 0x00C6C2F0> is callable
6. isinstance()
检查一个对象是不是给定类(或其子类)的实例
[python] view plaincopy
<span style="font-size:14px;">class A:
pass
class B:
pass
class C(A):
pass
class D(A,B):
pass
def dump(object):
print(object,'=>')
if isinstance(object,A):
print('A')
if isinstance(object,B):
print('B')
if isinstance(object,C):
print('C')
if isinstance(object,D):
print('D')
a = A()
b = B()
c = C()
d = D()
dump(a)
dump(b)
dump(c)
dump(d)
dump(0)
dump('string') </span>
结果:
<__main__.A object at 0x00BADA30> =>
A
<__main__.B object at 0x00C6C1F0> =>
B
<__main__.C object at 0x00C6C2F0> =>
A
C
<__main__.D object at 0x00C6C3B0> =>
A
B
D
0 =>
string =>
7. issubclass()
用于检查一个类对象是否与给定类相同,或者是给定类的子类,注意isinstance可以接收任何对象作为参数,而issubclass函数在接受非类对象参数时会引发TypeError异常。
8. eval()
将一个字符串作为python表达式值,你可以传递一串文本,简单的表达式,或者使用内建python函数。
[java] view plaincopy
<span style="font-size:14px;">def dump(expression):
result = eval(expression)
print(expression,'=>',result,type(result))
dump('1')
dump('1.0')
dump('str')
dump('1.0+2.0')
dump("'*'*10")
dump("len('world')")</span>
结果:
1 => 1 <class 'int'>
1.0 => 1.0 <class 'float'>
str => <class 'str'> <class 'type'>
1.0+2.0 => 3.0 <class 'float'>
'*'*10 => ********** <class 'str'>
len('world') => 5 <class 'int'>
9. compile()
Eval函数只针对简单的表达式,如果处理大块的代码,你应该使用compile和exec函数,成功执行后,compile函数会返回一个代码对象,你可以使用exec语句执行它。
例1:
[python] view plaincopy
<span style="font-size:14px;">BODY = "print('the ant, an introduction')"
code = compile(BODY,'<script>','exec')
print(code)
exec(code) </span>
结果:
<code object <module> at 0x00B0B5C0, file "<script>", line 1>
the ant, an introduction
例2:
[python] view plaincopy
<span style="font-size:14px;">class CodeGeneratorBackend:
def begin(self,tab='\t'):
self.code = []
self.tab = tab
self.level = 0
def end(self):
self.code.append('')
return compile(''.join(self.code),'<code>','exec')
def write(self,str):
self.code.append(self.tab*self.level+str)
def indent(self):
self.level = self.level + 1
def dedent(self):
if self.level == 0:
raise SyntaxError('internal error in code generator')
self.level = self.level - 1
c = CodeGeneratorBackend()
c.begin()
c.write('for i in range(5):')
c.indent()
c.write("print('code generator made easy')")
c.dedent()
exec(c.end())</span>
结果:
code generator made easy
code generator made easy
code generator made easy
code generator made easy
code generator made easy
以上就是python的一些内建函数,当然这个是不全的,希望自己能够活学活用吧。
内建的open/file函数用于创建,打开和编辑文件,而os模块提供了重命名和删除文件所需的函数
[python] view plaincopy
<span style="font-size:14px;">import os
def replace(file,search_for,replace_with):
back = os.path.splitext(file)[0]+'.bak'
print(back)
temp = os.path.splitext(file)[0]+'.tmp'
fi = open(file)
fo = open(temp,'w')
try:
os.remove(temp)
except os.error:
pass
for s in fi.readlines():
fo.write(str.replace(s, search_for,replace_with))
fi.close()
fo.close()
try:
os.remove(back)
except os.error:
pass
os.rename(file, back)
os.rename(temp,file)
file = 'g:/csy.txt'
replace(file,'hello','tjena')
replace(file,'tjena','hello') </span>
2. 处理目录
os模块也包含一些用于目录处理的函数,listdir函数返回给定目录中所有文件名(包括目录名)组成的列表
[python] view plaincopy
<span style="font-size:14px;">import os
for file in os.listdir('g:/my_paper'):
print(file)</span>
getcwd和chdir函数分别用于获得和改变当前工作目录
[python] view plaincopy
<span style="font-size:14px;">import os
cwd = os.getcwd()
print('1',cwd)
os.chdir('g:\\my_paper')
print('2',os.getcwd())
os.chdir(os.pardir)
print('3',os.getcwd())</span>
结果:
1 D:\Workspaces\MyEclipse 10\python1.0\src\Mysource\Module
2 g:\my_paper
3 g:\
makedirs和removedirs函数用于创建或删除目录层
[python] view plaincopy
<span style="font-size:14px;">import os
os.makedirs('g:\\test\\multiple\\levels')
fp = open('g:\\test\\multiple\\levels\\file.txt','w')
fp.write('inspector praline')
fp.close()
os.remove('e:\\test\\multiple\\levels\\file.txt')
os.removedirs('e:\\test\\multiple\\levels')</span>
removedirs函数会删除所给路径中最后一个目录下所有的空目录,而mkdir和rmdir函数只能处理单个目录级
3. 处理文件属性
Stat函数可以用来获取一个存在文件的信息,它返回一个类元组对象(stat_result对象,包括10个元素),依次是st_mode(权限模式),st_ino(inode number),st_dev(device),st_nlink(number of hard links),st_uid(所有者用户ID),st_gid(所有者所在组ID),st_size(文件大小,字节),st_atime(最近一次访问时间),st_mtime(最近修改时间),st_ctime(平台相关,Unix下的最近一次元数据/metadata修改时间,或者windows下的创建时间)
[python] view plaincopy
<span style="font-size:14px;">import os
import time
file = 'g:\\my_paper\\paper.wps'
def dump(st):
mode,ino,dev,nlink,uid,gid,size,atime,mtime,ctime=st
print('-size:',size,'bytes')
print('-owner:',uid,gid)
print('-created:',time.ctime(ctime))
print('-last accessed:',time.ctime(atime))
print('-last modified:',time.ctime(mtime))
print('-mode:',oct(mode))
print('-inode/dev:',ino,dev)
st = os.stat(file)
print('stat',file)
dump(st)
fp = open(file)
st = os.fstat(fp.fileno())
print('fstat',file)
dump(st)</span>
stat模块包含了很多可以处理该返回对象的常量及函数,下面代码展示了其中的一些,可以使用chmod和utime函数修改文件的权限模式和时间属性。
[python] view plaincopy
<span style="font-size:14px;">import time,stat,os
infile = 'g:\\samples\\sample.txt'
outfile = 'g:\\sample.txt'
fi = open(infile,'rb')
fo = open(outfile,'wb')
while 1:
s = fi.read(10000)
if not s:
break
fo.write(s)
fi.close()
fo.close()
st = os.stat(infile)
os.chmod(outfile, stat.S_IMODE(st[stat.ST_MODE]))
os.utime(outfile, (st[stat.ST_ATIME], st[stat.ST_MTIME]))
print('original','=>')
print('mode',oct(stat.S_IMODE(st[stat.ST_MODE])))
print('atime',time.ctime(st[stat.ST_ATIME]))
print('mtime',time.ctime(st[stat.ST_MTIME]))
print('copy','=>')
st = os.stat(outfile)
print('mode',oct(stat.S_IMODE(st[stat.ST_MODE])))
print('atime',time.ctime(st[stat.ST_ATIME]))
print('mtime',time.ctime(st[stat.ST_MTIME]))</span>
结果:
original =>
mode 0o666
atime Mon Dec 17 10:18:29 2012
mtime Mon Dec 17 10:18:41 2012
copy =>
mode 0o666
atime Mon Dec 17 10:18:29 2012
mtime Mon Dec 17 10:18:41 2012
4. 处理进程
system 函数在当前进程下执行一个新命令,并等待它完成
[python] view plaincopy
<span style="font-size:14px;">import os
if os.name == 'nt':
command = 'dir'
else:
command = 'ls -l'
os.system(command)</span>
处理进程还有好多命令在这里就不一一列举。
5. os.path模块
5.1处理文件名
Os.path模块包含了许多与平台无关的处理长文件名的函数,也就是说你不需要处理前后斜杠,冒号等
[python] view plaincopy
<span style="font-size:14px;">import os
filename = 'my/little/pony'
print('using',os.name,'...')
print('split','=>',os.path.split(filename))
print('splitext','=>',os.path.splitext(filename))
print('dirname','=>',os.path.dirname(filename))
print('basename','=>',os.path.basename(filename))
print('join','=>',os.path.join(os.path.dirname(filename),os.path.basename(filename)))</span>
结果:
using nt ...
split => ('my/little', 'pony')
splitext => ('my/little/pony', '')
dirname => my/little
basename => pony
join => my/little\pony
6. stat模块
[python] view plaincopy
<span style="font-size:14px;">import stat,os,time
st = os.stat('g:\\samples/sample.txt')
print('mode','=>',oct(stat.S_IMODE(st[stat.ST_MODE])))
print('type','=>')
if stat.S_ISDIR(st[stat.ST_MODE]):
print('DIRECTORY')
if stat.S_ISREG(st[stat.ST_MODE]):
print('REGULAR')
if stat.S_ISLNK(st[stat.ST_MODE]):
print('LINK')
print('size','=>',st[stat.ST_SIZE])
print('last accessed','=>',time.ctime(st[stat.ST_ATIME]))
print('last modified','=>',time.ctime(st[stat.ST_MTIME]))
print('inode changed','=>',time.ctime(st[stat.ST_CTIME]))</span>
结果:
mode => 0o666
type =>
REGULAR
size => 0
last accessed => Mon Dec 17 10:51:24 2012
last modified => Mon Dec 17 10:51:24 2012
inode changed => Mon Dec 17 10:51:24 2012
7. string模块
[python] view plaincopy
<span style="font-size:14px;">text = "Monty Python's Flying Circus"
print('upper','=>',text.upper())
print('lower','=>',text.lower())
print('split','=>',text.split())
print('join','=>',text.join(text.split()))
print('replace','=>',text.replace('python','java'))
print('find','=>',text.find('python'),text.find('java'))
print('count','=>',text.count('n'))</span>
结果:
upper => MONTY PYTHON'S FLYING CIRCUS
lower => monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join => MontyMonty Python's Flying CircusPython'sMonty Python's Flying CircusFlyingMonty Python's Flying CircusCircus
replace => Monty Python's Flying Circus
find => -1 -1
count => 3
8. copy模块
copy模块包含两个函数,用来拷贝对象,copy(object) => object创建给定对象的浅/浅层(shallow)拷贝,这里的浅/浅层(shallow)拷贝的意思是复制对象本身,但当对象时一个容器时,它的成员任然指向原来的成员对象。
[python] view plaincopy
<span style="font-size:14px;">import copy
a = [[1],[2],[3]]
b = copy.copy(a)
print('before','=>',a,b)
a[0][0] = 0
a[1] = None
print('after','=>',a,b)</span>
结果:
before => [[1], [2], [3]] [[1], [2], [3]]
after => [[0], None, [3]] [[0], [2], [3]]
其实也可以使用[:]语句来对列表进行浅层复制,相反了deepcopy(object) => object创建一个对象的深层拷贝,当对象是一个容器时,所有的成员都被递归的复制了。
[python] view plaincopy
<span style="font-size:14px;">import copy
a = [[1],[2],[3]]
b = copy.deepcopy(a)
print('before','=>',a,b)
a[0][0] = 0
a[1] = None
print('after','=>',a,b)</span>
结果:
before => [[1], [2], [3]] [[1], [2], [3]]
after => [[0], None, [3]] [[1], [2], [3]]
9. sys模块
9.1 解释器启动后,argv解表包含了传递给脚本的所有参数,列表的第一个元素为脚本自身的名称。
[python] view plaincopy
<span style="font-size:14px;">import sys
print('script name is',sys.argv[0])
if len(sys.argv)>1:
print('there are',len(sys.argv)-1,'arguments:')
for arg in sys.argv[1:]:
print(arg)
else:
print('there are no arguments!')</span>
结果:
script name is D:\Workspaces\MyEclipse 10\python1.0\src\Mysource\Module\Test.py
there are no arguments!
9.2 stdin,stdout以及stderr
[python] view plaincopy
<span style="font-size:14px;">import sys
class Redirect:
def __init__(self,stdout):
self.stdout = stdout
def write(self,s):
self.stdout.write(s.lower())
old_stdout = sys.stdout
sys.stdout = Redirect(sys.stdout)
print('HEJA SVERIGE')
print('FRISKT HUM')
sys.stdout = old_stdout
print('MLASJDL;JG;')</span>
结果:
heja sverige
friskt hum
MLASJDL;JG;
要重定向输出只要创建一个对象,并实现它的write方法。
posted on 2013-04-22 21:53 androidme 阅读(1621) 评论(0) 编辑 收藏 举报