Chinaunix首页 | 论坛 | 博客
  • 博客访问: 749950
  • 博文数量: 231
  • 博客积分: 3217
  • 博客等级: 中校
  • 技术积分: 2053
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-04 12:01
文章分类

全部博文(231)

文章存档

2015年(1)

2013年(10)

2012年(92)

2011年(128)

分类: LINUX

2012-05-25 10:30:56

模块是程序,任何python程序都可以作为模块导入。一个简单的模块:hello.py

点击(此处)折叠或打开

  1. def hello():
  2.     print "hello world!"
  3. def test():
  4.     hello()

  5. if __name__=='__main__':test()
>>>import sys, pprint
>>> pprint.pprint(sys.path)    #查看系统模块的路径
['',
 '/usr/lib/python2.6',
 '/usr/lib/python2.6/plat-linux2',
 '/usr/lib/python2.6/lib-tk',
 '/usr/lib/python2.6/lib-old',
 '/usr/lib/python2.6/lib-dynload',
 '/usr/lib/python2.6/dist-packages',
 '/usr/lib/python2.6/dist-packages/PIL',
 '/usr/lib/python2.6/dist-packages/gst-0.10',
 '/usr/lib/pymodules/python2.6',
 '/usr/lib/python2.6/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.6/gtk-2.0',
 '/usr/local/lib/python2.6/dist-packages']
>>> sys.path.append('/root/hello')    #添加新的路径
>>> pprint.pprint(sys.path)           #查看是否添加进去
['',
 '/usr/lib/python2.6',
 '/usr/lib/python2.6/plat-linux2',
 '/usr/lib/python2.6/lib-tk',
 '/usr/lib/python2.6/lib-old',
 '/usr/lib/python2.6/lib-dynload',
 '/usr/lib/python2.6/dist-packages',
 '/usr/lib/python2.6/dist-packages/PIL',
 '/usr/lib/python2.6/dist-packages/gst-0.10',
 '/usr/lib/pymodules/python2.6',
 '/usr/lib/python2.6/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.6/gtk-2.0',
 '/usr/local/lib/python2.6/dist-packages',
 '/root/hello']                               #已经能够添加成功
>>> dir(sys.path)                                #使用dir查看sys.path有哪些函数功能
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '_
 

>>> sys.path.remove('/root/hello')      #删除添加的路径
>>> pprint.pprint(sys.path)             #已经删除
['',
 '/usr/lib/python2.6',
 '/usr/lib/python2.6/plat-linux2',
 '/usr/lib/python2.6/lib-tk',
 '/usr/lib/python2.6/lib-old',
 '/usr/lib/python2.6/lib-dynload',
 '/usr/lib/python2.6/dist-packages',
 '/usr/lib/python2.6/dist-packages/PIL',
 '/usr/lib/python2.6/dist-packages/gst-0.10',
 '/usr/lib/pymodules/python2.6',
 '/usr/lib/python2.6/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.6/gtk-2.0',
 '/usr/local/lib/python2.6/dist-packages']

>>> sys.path.append('/root/ff') #添加/root/ff到系统中
>>> pprint.pprint(sys.path)
['',
 '/usr/lib/python26.zip',
 '/usr/lib/python2.6',
 '/usr/lib/python2.6/plat-linux2',
 '/usr/lib/python2.6/lib-tk',
 '/usr/lib/python2.6/lib-old',
 '/usr/lib/python2.6/lib-dynload',
 '/usr/lib/python2.6/site-packages',
 '/usr/lib/python2.6/site-packages/gst-0.10',
 '/usr/lib/python2.6/site-packages/gtk-2.0',
 '/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info',
 '/usr/lib/python2.6/site-packages/webkit-1.0',
 '/root/ff']
>>> import hello    #调用模块hello.py
>>> hello.hello()
hello world
>>> hello.test()
hello world
变量__name__为了告知模块本身是作为程序运行还是导入到到他的程序,在主程序中变量__name____main__,在模块中__name__是模块的名字。

第二种方法:告诉编译器去哪里找模块。在linux系统下,需要设置环境变量PYTHON.  export PYTHON=$PYTHON:/root/ff

 

 

为了能够更好的组织好模块,可以将他们分组为包,包可以包含其他的模块。包就是模块所在的目录,为了让python将其作为包对待,它必须包含一个命名的__init__.py的文件(模块),如果将它作为普通模块导入,__init__文件的内容就是包的内容。比如在ff目录下有__init__colors.pyshapes.py

import ff  #import the ff packages

import ff.colors  #import the colors modules

from ff import shapes  #import the shapes module

 

>>> dir(copy)  #查看copy的函数
['Error', 'PyStringMap', '_EmptyClass', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_dispatch', '_copy_immutable', '_copy_inst', '_copy_with_constructor', '_copy_with_copy_method', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_inst', '_deepcopy_list', '_deepcopy_tuple', '_keep_alive', '_reconstruct', '_test', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't']
>>> copy.__all__     #过滤掉一些函数
['Error', 'copy', 'deepcopy']
>>> from copy import PyStringMap   #想要输出不是被包含的函数只能显示调用
>>> copy.__all__
['Error', 'copy', 'deepcopy']
>>> help(copy.copy)               #使用help帮忙查看函数功能

>>> print copy.copy.__doc__        #查看文档信息

Shallow copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.

>>> print range.__doc__
range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
   

sysos模块:

>>> print sys.__doc__
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules

displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
  To customize printing in an interactive session or to install a custom
  top-level exception handler, assign other functions to replace these.

exitfunc -- if sys.exitfunc exists, this routine is called when Python exits
  Assigning to sys.exitfunc is deprecated; use the atexit module instead.

stdin -- standard input file object; used by raw_input() and input()
stdout -- standard output file object; used by the print statement
stderr -- standard error object; used for error messages
  By assigning other file objects (or objects that behave like files)
  to these, it is possible to redirect all of the interpreter's I/O.

last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
  These three are only available in an interactive session after a
  traceback has been printed.

exc_type -- type of exception currently being handled
exc_value -- value of exception currently being handled
exc_traceback -- traceback of exception currently being handled
  The function exc_info() should be used instead of these three,
  because it is thread-safe.

Static objects:

float_info -- a dict with information about the float inplementation.
long_info -- a struct sequence with information about the long implementation.
maxint -- the largest supported integer (the smallest is -maxint-1)
maxsize -- the largest supported length of containers.
maxunicode -- the largest supported character
builtin_module_names -- tuple of module names built into this interpreter
version -- the version of this interpreter as a string
version_info -- version information as a named tuple
hexversion -- version information encoded as a single integer
copyright -- copyright notice pertaining to this interpreter
platform -- platform identifier
executable -- pathname of this Python interpreter
prefix -- prefix used to find the Python library
exec_prefix -- prefix used to find the machine-specific Python library
float_repr_style -- string indicating the style of repr() output for floats
dllhandle -- [Windows only] integer handle of the Python DLL
winver -- [Windows only] version number of the Python DLL
__stdin__ -- the original stdin; don't touch!
__stdout__ -- the original stdout; don't touch!
__stderr__ -- the original stderr; don't touch!
__displayhook__ -- the original displayhook; don't touch!
__excepthook__ -- the original excepthook; don't touch!

Functions:

displayhook() -- print an object to the screen, and save it in __builtin__._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exc_clear() -- clear the exception state for the current thread
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setcheckinterval() -- control how often the interpreter checks for events
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function

>>> print sys.platform
win32
>>> import os
>>> print os.__doc__
OS routines for Mac, NT, or Posix depending on what system we're on.

This exports:
  - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
  - os.path is one of the modules posixpath, or ntpath
  - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'
  - os.curdir is a string representing the current directory ('.' or ':')
  - os.pardir is a string representing the parent directory ('..' or '::')
  - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  - os.extsep is the extension separator ('.' or '/')
  - os.altsep is the alternate pathname separator (None or '/')
  - os.pathsep is the component separator used in $PATH etc
  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  - os.defpath is the default search path for executables
  - os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).

 

sys模块中:

argv :命令行参数,包括脚本名称

exit([argv]):退出当前的程序,可选参数为给定的返回值或者错误信息

modules:映射模块名字到载入模块的字典

path:查找模块所在目录的目录名列表

platform: 类似sunos或者win32的平台的标示符

stdin:标准输入流--一个类文件对象

stdout:标准输出流--一个类文件对象

stderr:标准错误流--一个类文件对象

 

so模块中:

environ:对环境变量进行映射

systerm(command):对子shell中执行操作系统命令

sep:路径中的分隔符

pathsep:分割路径的分隔符

linesep:行分隔符('\n','\r ')
urandom(n):返回n字节的加密强随机数据。

os.environ['PYTHON']:访问系统环境变量

os.system函数用于运行外部函数,execv也可以os.system('/usr/bin/firefox')

 

>>> import webbrowser  #调用webbrowser模块打开网页
>>> webbrowser.open('')

阅读(982) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~