您的位置:首页 > 编程语言 > Python开发

python模块

2016-03-17 14:39 686 查看
一.模块搜索路径
模块其实就是一个一个python程序,可以使用三种方法让你的模块可以被发现进而导入到其它程序中

1.将你的程序模块放到sys.path路径中

查看当前的sys.path路径,可以使用printsys.path,或者使用pprint的pprint,一般是放到site-packages目录中

>>>importpprint
>>>importsys
>>>pprint.pprint(sys.path)
['',
'C:\\Windows\\system32\\python27.zip',
'D:\\ProgramFiles\\python27\\DLLs',
'D:\\ProgramFiles\\python27\\lib',
'D:\\ProgramFiles\\python27\\lib\\plat-win',
'D:\\ProgramFiles\\python27\\lib\\lib-tk',
'D:\\ProgramFiles\\python27',
'D:\\ProgramFiles\\python27\\lib\\site-packages']


2.将你的程序路径添加到sys.path中(不推荐)

使用append方法,在sys.path中添加你的路径,这个方法在你退出python后,重新importsys的时候会失效,需要再次append

>>>sys.path.append('c:\\python')
>>>pprint.pprint(sys.path)
['',
'C:\\Windows\\system32\\python27.zip',
'D:\\ProgramFiles\\python27\\DLLs',
'D:\\ProgramFiles\\python27\\lib',
'D:\\ProgramFiles\\python27\\lib\\plat-win',
'D:\\ProgramFiles\\python27\\lib\\lib-tk',
'D:\\ProgramFiles\\python27',
'D:\\ProgramFiles\\python27\\lib\\site-packages',
'c:\\python']


3.修改PYTHONPATH环境变量,添加你的程序路径(推荐)

例如在linux环境下设置PYTHONPATH环境变量即可

[root@python~]#exportPYTHONPATH=/root/


二.模块定义

我们在python命令行中查看__name__的时候,__name__变量总是等于__main__,而当我们使用模块调用的时候__name__等于模块的名字:

>>>__name__
'__main__'


>>>importhello
>>>hello.__name__
'hello'


那么这就给我们提供了识别程序是以主程序运行还是以模块导入方式来运行的.所以我们一般在写一个模块的时候在主体部分写上if__name__=='__main__':

例如下面例子当我们以程序运行的时候就打印helloworld,而当我们以模块方式导入的时候,只有在调用的时候才打印helloworld

#!/usr/bin/envpython
defaa():
print'helloworld'
if__name__=='__main__':
aa()


三.模块导入方法

模块的导入方法也有三种

1.importsys可以起别名importsysass

2.fromsysimportpath或者fromsysimport*这个也可以起别名fromsysimportpathasp,这种的方式好处是可以只导入你想要的部分,而且使用的时候不需要加模块的名字

3.使用内建函数mymodule=__import__(’module_name’)

使用reload(模块名)来重新导入模块

四.包

为了组织好模块,我们可以将他们分组为包,即一个包可以包含多个模块.包就是模块所在的目录,为了让python将其作为包对待,需要在目录下建立一个__init__.py的文件,哪怕是空文件也行,但是必须有

例如PYTHONPATH为/root目录,在root目录下我们新建一个pack的目录,在pack目录下建立一个__init__.py和hello.py

[root@pythonpack]#pwd
/root/pack
[root@pythonpack]#ls
hello.py__init__.py
[root@pythonpack]#cat__init__.py


导入的时候使用包名.模块名来导入:

>>>importpack.hello
>>>pack.hello.aa()
helloworld


五.查看模块

使用dir(模块名)来查看模块所具有哪些函数,可以使用列表推导式过滤掉以__开头的函数,这些__函数并不是给模块外部使用的

>>>[nfornindir(sys)ifnotn.startswith('_')]
['api_version','argv','builtin_module_names','byteorder','call_tracing','callstats','copyright','displayhook','d
llhandle','dont_write_bytecode','exc_clear','exc_info','exc_type','excepthook','exec_prefix','executable','exit'
,'flags','float_info','float_repr_style','getcheckinterval','getdefaultencoding','getfilesystemencoding','getprof
ile','getrecursionlimit','getrefcount','getsizeof','gettrace','getwindowsversion','hexversion','last_type','last
_value','long_info','maxint','maxsize','maxunicode','meta_path','modules','path','path_hooks','path_importer_ca
che','platform','prefix','ps1','ps2','py3kwarning','setcheckinterval','setdefaultencoding','setprofile','setrec
ursionlimit','settrace','stderr','stdin','stdout','subversion','version','version_info','warnoptions','winver']


使用help(模块名)来查看模块的帮助

使用模块名.__doc__来查看模块的文档信息

>>>sys.__doc__
"Thismoduleprovidesaccesstosomeobjectsusedormaintainedbythe\ninterpreterandtofunctionsthatinteractstron
glywiththeinterpreter.\n\nDynamicobjects:\n\nargv--commandlinearguments;argv[0]isthescriptpathnameifknown
\npath--modulesearchpath;path[0]isthescriptdirectory,else''\nmodules--dictionaryofloadedmodules\n\ndispl
ayhook--calledtoshowresultsinaninteractivesession\nexcepthook--calledtohandleanyuncaughtexceptionother
thanSystemExit\nTocustomizeprintinginaninteractivesessionortoinstallacustom\ntop-levelexceptionhandler
,assignotherfunctionstoreplacethese.\n\nexitfunc--ifsys.exitfuncexists,thisroutineiscalledwhenPythonexi
ts\nAssigningtosys.exitfuncisdeprecated;usetheatexitmoduleinstead.\n\nstdin--standardinputfileobject;us
edbyraw_input()andinput()\nstdout--standardoutputfileobject;usedbytheprintstatement\nstderr--standarder
rorobject;usedforerrormessages\nByassigningotherfileobjects(orobjectsthatbehavelikefiles)\ntothese,
itispossibletoredirectalloftheinterpreter'sI/O.\n\nlast_type--typeoflastuncaughtexception\nlast_value--
valueoflastuncaughtexception\nlast_traceback--tracebackoflastuncaughtexception\nThesethreeareonlyavailab
leinaninteractivesessionaftera\ntracebackhasbeenprinted.\n\nexc_type--typeofexceptioncurrentlybeinghan
dled\nexc_value--valueofexceptioncurrentlybeinghandled\nexc_traceback--tracebackofexceptioncurrentlybeingh
andled\nThefunctionexc_info()shouldbeusedinsteadofthesethree,\nbecauseitisthread-safe.\n\nStaticobjects
:\n\nfloat_info--adictwithinformationaboutthefloatinplementation.\nlong_info--astructsequencewithinformat
ionaboutthelongimplementation.\nmaxint--thelargestsupportedinteger(thesmallestis-maxint-1)\nmaxsize--the
largestsupportedlengthofcontainers.\nmaxunicode--thelargestsupportedcharacter\nbuiltin_module_names--tupleof
modulenamesbuiltintothisinterpreter\nversion--theversionofthisinterpreterasastring\nversion_info--versi
oninformationasanamedtuple\nhexversion--versioninformationencodedasasingleinteger\ncopyright--copyrightn
oticepertainingtothisinterpreter\nplatform--platformidentifier\nexecutable--absolutepathoftheexecutablebin
aryofthePythoninterpreter\nprefix--prefixusedtofindthePythonlibrary\nexec_prefix--prefixusedtofindthe
machine-specificPythonlibrary\nfloat_repr_style--stringindicatingthestyleofrepr()outputforfloats\ndllhandle
--[Windowsonly]integerhandleofthePythonDLL\nwinver--[Windowsonly]versionnumberofthePythonDLL\n__stdin__
--theoriginalstdin;don'ttouch!\n__stdout__--theoriginalstdout;don'ttouch!\n__stderr__--theoriginalstderr
;don'ttouch!\n__displayhook__--theoriginaldisplayhook;don'ttouch!\n__excepthook__--theoriginalexcepthook;do
n'ttouch!\n\nFunctions:\n\ndisplayhook()--printanobjecttothescreen,andsaveitin__builtin__._\nexcepthook()-
-printanexceptionanditstracebacktosys.stderr\nexc_info()--returnthread-safeinformationaboutthecurrentexc
eption\nexc_clear()--cleartheexceptionstateforthecurrentthread\nexit()--exittheinterpreterbyraisingSyste
mExit\ngetdlopenflags()--returnsflagstobeusedfordlopen()calls\ngetprofile()--gettheglobalprofilingfunctio
n\ngetrefcount()--returnthereferencecountforanobject(plusone:-)\ngetrecursionlimit()--returnthemaxrecurs
iondepthfortheinterpreter\ngetsizeof()--returnthesizeofanobjectinbytes\ngettrace()--gettheglobaldebug
tracingfunction\nsetcheckinterval()--controlhowoftentheinterpreterchecksforevents\nsetdlopenflags()--setthe
flagstobeusedfordlopen()calls\nsetprofile()--settheglobalprofilingfunction\nsetrecursionlimit()--setthe
maxrecursiondepthfortheinterpreter\nsettrace()--settheglobaldebugtracingfunction\n"


还可以直接查看源代码,源代码位置可以查看模块的__file__方法,有的模块没有__file__方法的只能到sys.path中搜索了.对于pyc文件,只需要查看py文件即可

>>>importcopy
>>>printcopy.__file__
/usr/lib64/python2.6/copy.pyc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: