python学习之路-第四天-模块

模块

  • sys模块

sys.argv:参数列表,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]。注意,Python从0开始计数,而非从1开始。

sys.path:包含输入模块的目录名列表

  • .pyc文件,字节码文件,用于python把模块编译成字节码,这样可以保证平台无关性和下次调用时的效率

  • 模块的__name__:每个Python模块都有它的__name__,如果它是'main',这说明这个模块被用户单独运行,我们可以进行相应的恰当操作。

示例:

#!/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
#被import使用
$ python
>>> import using_name
I am being imported from another module
>>>
  • 使用自己创建的模块:
  1. 与正常的函数或者变量书写一样,不过是需要导入的时候,输入,模块名+"."+函数名()/变量名,进行调用就行了

  2. 可以导入的模块必须在当前的工作目录,或者在sys.path所列目录之一

  • dir():参数提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。

示例:

$ python
>>> import sys
>>> dir(sys) # get list of attributes for sys module
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type',
'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval',
'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding',
'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
'meta_path','modules', 'path', 'path_hooks', 'path_importer_cache',
'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
'version', 'version_info', 'warnoptions']
>>> dir() # get list of attributes for current module
['__builtins__', '__doc__', '__name__', 'sys']
>>> a = 5 # create a new variable 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>> del a # delete/remove a name
>>>
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']
原文地址:https://www.cnblogs.com/qjx-2016/p/7843903.html