第8章 模块
- #!/usr/bin/python
- #Filename using_sys.py
- import sys
- print 'The command line arguments are:'
- for i in sys.argv: #sys.argv 是字串列表,包含了命令参数的列表
- print i
- print '\n\nThe PYTHONPATH is', sys.path, '\n'
$python using_sys.py 1 2 3 5
The command line arguments are:
using_sys.py
1
2
3
5
The PYTHONPATH is ['/home/Administrator/temp', '/usr/lib/python26.zip', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-cygwin', '/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/PIL', '/usr/lib/python2.6/site-packages/gtk-2.0']
- #!/usr/bin/python
- #Filename using_name.py
- if __name__ == '__main__':
- print 'This program is being run by itself'
- else:
- print 'I am being imported from another module'
$python using_name.py
This program is being run by itself
$python
>>>import using_name
I am being imported from another module
- #!/usr/bin/python
- #Filename mymodule.py
- def sayhi():
- print 'Hi,this is mymodule speaking.'
- version = '0.1'
- #end of mymodule.py
- #!/usr/bin/python
- #Filename mymodule_demo.py
- import mymodule
- mymodule.sayhi()
- print 'Version', mymodule.version
$python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
- #!/usr/bin/python
- #Filename mymodule_demo2.py
- from mymodule import sayhi, version
- #Alternative:
- #from mymodule import *
- sayhi()
- print 'Version', version
$ python
Python 2.6.8 (unknown, Jun 9 2012, 11:30:32)
[GCC 4.5.3] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>> a = 5
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'sys']
>>> del a
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'sys']
>>>