python模块

一.模块搜索路径
模块其实就是一个一个python程序,可以使用三种方法让你的模块可以被发现进而导入到其它程序中
1.将你的程序模块放到sys.path路径中
查看当前的sys.path路径,可以使用print sys.path,或者使用pprint的pprint,一般是放到 site-packages 目录中
  
  
>>> import pprint
>>> import sys
>>> pprint.pprint(sys.path)
['',
'C:\\Windows\\system32\\python27.zip',
'D:\\Program Files\\python27\\DLLs',
'D:\\Program Files\\python27\\lib',
'D:\\Program Files\\python27\\lib\\plat-win',
'D:\\Program Files\\python27\\lib\\lib-tk',
'D:\\Program Files\\python27',
'D:\\Program Files\\python27\\lib\\site-packages']
2.将你的程序路径添加到sys.path中(不推荐)
使用append方法,在sys.path中添加你的路径 ,这个方法在你退出python后,重新import sys的时候会失效,需要再次append
   
   
>>> sys.path.append('c:\\python')
>>> pprint.pprint(sys.path)
['',
'C:\\Windows\\system32\\python27.zip',
'D:\\Program Files\\python27\\DLLs',
'D:\\Program Files\\python27\\lib',
'D:\\Program Files\\python27\\lib\\plat-win',
'D:\\Program Files\\python27\\lib\\lib-tk',
'D:\\Program Files\\python27',
'D:\\Program Files\\python27\\lib\\site-packages',
'c:\\python']

3.修改PYTHONPATH环境变量,添加你的程序路径(推荐)
例如在linux环境下设置PYTHONPATH环境变量即可
   
   
[root@python ~]# export PYTHONPATH=/root/

二.模块定义
我们在python命令行中查看__name__的时候,__name__变量总是等于__main__,而当我们使用模块调用的时候__name__等于模块的名字:
   
   
>>> __name__
'__main__'
    
    
>>> import hello
>>> hello.__name__
'hello'
那么这就给我们提供了识别程序是以主程序运行还是以模块导入方式来运行的.所以我们一般在写一个模块的时候在主体部分写上if __name__=='__main__':
例如下面例子当我们以程序运行的时候就打印hello world,而当我们以模块方式导入的时候,只有在调用的时候才打印hello world
   
   
#!/usr/bin/env python
def aa():
print 'hello world'
 
if __name__=='__main__':
aa()
三.模块导入方法
模块的导入方法也有三种
1.import sys 可以起别名import sys as s
2.from sys import path或者from sys import * 这个也可以起别名from sys import path as p,这种的方式好处是可以只导入你想要的部分,而且使用的时候不需要加模块的名字
3.使用内建函数mymodule = __import__ (’module_name’)
使用reload(模块名)来重新导入模块

四.包
为了组织好模块,我们可以将他们分组为包,即一个包可以包含多个模块.包就是模块所在的目录,为了让python将其作为包对待,需要在目录下建立一个__init__.py的文件,哪怕是空文件也行,但是必须有
例如PYTHONPATH为/root目录,在root目录下我们新建一个pack的目录,在pack目录下建立一个__init__.py和hello.py
   
   
[root@python pack]# pwd
/root/pack
[root@python pack]# ls
hello.py __init__.py
[root@python pack]# cat __init__.py
导入的时候使用包名.模块名来导入:
   
   
>>> import pack.hello
>>> pack.hello.aa()
hello world
五.查看模块
使用dir(模块名)来查看模块所具有哪些函数,可以使用列表推导式过滤掉以__开头的函数,这些__函数并不是给模块外部使用的
   
   
>>> [n for n in dir(sys) if not n.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__
"This module provides access to some objects used or maintained by the\ninterpreter and to functions that interact stron
gly with the interpreter.\n\nDynamic objects:\n\nargv -- command line arguments; argv[0] is the script pathname if known
\npath -- module search path; path[0] is the script directory, else ''\nmodules -- dictionary of loaded modules\n\ndispl
ayhook -- called to show results in an interactive session\nexcepthook -- called to handle any uncaught exception other
than SystemExit\n To customize printing in an interactive session or to install a custom\n top-level exception handler
, assign other functions to replace these.\n\nexitfunc -- if sys.exitfunc exists, this routine is called when Python exi
ts\n Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\nstdin -- standard input file object; us
ed by raw_input() and input()\nstdout -- standard output file object; used by the print statement\nstderr -- standard er
ror object; used for error messages\n By assigning other file objects (or objects that behave like files)\n to these,
it is possible to redirect all of the interpreter's I/O.\n\nlast_type -- type of last uncaught exception\nlast_value --
value of last uncaught exception\nlast_traceback -- traceback of last uncaught exception\n These three are only availab
le in an interactive session after a\n traceback has been printed.\n\nexc_type -- type of exception currently being han
dled\nexc_value -- value of exception currently being handled\nexc_traceback -- traceback of exception currently being h
andled\n The function exc_info() should be used instead of these three,\n because it is thread-safe.\n\nStatic objects
:\n\nfloat_info -- a dict with information about the float inplementation.\nlong_info -- a struct sequence with informat
ion about the long implementation.\nmaxint -- the largest supported integer (the smallest is -maxint-1)\nmaxsize -- the
largest supported length of containers.\nmaxunicode -- the largest supported character\nbuiltin_module_names -- tuple of
module names built into this interpreter\nversion -- the version of this interpreter as a string\nversion_info -- versi
on information as a named tuple\nhexversion -- version information encoded as a single integer\ncopyright -- copyright n
otice pertaining to this interpreter\nplatform -- platform identifier\nexecutable -- absolute path of the executable bin
ary of the Python interpreter\nprefix -- prefix used to find the Python library\nexec_prefix -- prefix used to find the
machine-specific Python library\nfloat_repr_style -- string indicating the style of repr() output for floats\ndllhandle
-- [Windows only] integer handle of the Python DLL\nwinver -- [Windows only] version number of the Python DLL\n__stdin__
-- the original stdin; don't touch!\n__stdout__ -- the original stdout; don't touch!\n__stderr__ -- the original stderr
; don't touch!\n__displayhook__ -- the original displayhook; don't touch!\n__excepthook__ -- the original excepthook; do
n't touch!\n\nFunctions:\n\ndisplayhook() -- print an object to the screen, and save it in __builtin__._\nexcepthook() -
- print an exception and its traceback to sys.stderr\nexc_info() -- return thread-safe information about the current exc
eption\nexc_clear() -- clear the exception state for the current thread\nexit() -- exit the interpreter by raising Syste
mExit\ngetdlopenflags() -- returns flags to be used for dlopen() calls\ngetprofile() -- get the global profiling functio
n\ngetrefcount() -- return the reference count for an object (plus one :-)\ngetrecursionlimit() -- return the max recurs
ion depth for the interpreter\ngetsizeof() -- return the size of an object in bytes\ngettrace() -- get the global debug
tracing function\nsetcheckinterval() -- control how often the interpreter checks for events\nsetdlopenflags() -- set the
flags to be used for dlopen() calls\nsetprofile() -- set the global profiling function\nsetrecursionlimit() -- set the
max recursion depth for the interpreter\nsettrace() -- set the global debug tracing function\n"
还可以直接查看源代码,源代码位置可以查看模块的__file__方法,有的模块没有__file__方法的只能到sys.path中搜索了.对于pyc文件,只需要查看py文件即可
   
   
>>> import copy
>>> print copy.__file__
/usr/lib64/python2.6/copy.pyc












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值