• 模块


    1.模块:使程序更容易维护;一个.py文件就是一个模块
    好处:
    1.提高可维护
    2.可重用
    3.避免函数名,变量名冲突
    分类:
    1.内置标准模块(标准库)执行help('modules')查看所有python自带的和下载第三方模块的列表
    2.第三方开源模块,可通过pip install 模块名 联网安装
    3.自定义模块

    --------------------------------------------------------
    1.1.所有内置和第三方模块:

    >>> help('modules')
    Please wait a moment while I gather a list of all available modules...
    
    ClearWindow         atexit              http                runscript
    __future__          audioop             hyperparser         sched
    __main__            autocomplete        idle                scrolledlist
    _ast                autocomplete_w      idle_test           search
    _asyncio            autoexpand          idlelib             searchbase
    _bisect             base64              imaplib             searchengine
    _blake2             bdb                 imghdr              secrets
    _bootlocale         binascii            imp                 select
    _bz2                binhex              importlib           selectors
    _codecs             bisect              inspect             setuptools
    _codecs_cn          browser             io                  shelve
    _codecs_hk          builtins            iomenu              shlex
    _codecs_iso2022     bz2                 ipaddress           shutil
    _codecs_jp          cProfile            itertools           signal
    _codecs_kr          calendar            json                site
    _codecs_tw          calltip_w           keyword             smtpd
    _collections        calltips            lib2to3             smtplib
    _collections_abc    cgi                 linecache           sndhdr
    _compat_pickle      cgitb               locale              socket
    _compression        chardet             logging             socketserver
    _csv                chunk               lzma                sqlite3
    _ctypes             cmath               macosx              sre_compile
    _ctypes_test        cmd                 macpath             sre_constants
    _datetime           code                macurl2path         sre_parse
    _decimal            codecontext         mailbox             ssl
    _dummy_thread       codecs              mailcap             stackviewer
    _elementtree        codeop              mainmenu            stat
    _findvs             collections         marshal             statistics
    _functools          colorizer           math                statusbar
    _hashlib            colorsys            mimetypes           string
    _heapq              compileall          mmap                stringprep
    _imp                concurrent          modulefinder        struct
    _io                 config              msilib              subprocess
    _json               config_key          msvcrt              sunau
    _locale             configdialog        multicall           symbol
    _lsprof             configparser        multiprocessing     symtable
    _lzma               contextlib          netrc               sys
    _markupbase         copy                nntplib             sysconfig
    _md5                copyreg             nt                  tabnanny
    _msi                crypt               ntpath              tarfile
    _multibytecodec     csv                 nturl2path          telnetlib
    _multiprocessing    ctypes              numbers             tempfile
    _opcode             curses              opcode              test
    _operator           datetime            operator            textview
    _osx_support        dbm                 optparse            textwrap
    _overlapped         debugger            os                  this
    _pickle             debugger_r          outwin              threading
    _pyclbr             debugobj            paragraph           time
    _pydecimal          debugobj_r          parenmatch          timeit
    _pyio               decimal             parser              tkinter
    _random             delegator           pathbrowser         token
    _sha1               difflib             pathlib             tokenize
    _sha256             dis                 pdb                 tooltip
    _sha3               distutils           percolator          trace
    _sha512             doctest             pickle              traceback
    _signal             dummy_threading     pickletools         tracemalloc
    _sitebuiltins       dynoption           pip                 tree
    _socket             easy_install        pipes               tty
    _sqlite3            editor              pkg_resources       turtle
    _sre                email               pkgutil             turtledemo
    _ssl                encodings           platform            types
    _stat               ensurepip           plistlib            typing
    _string             enum                poplib              undo
    _strptime           errno               posixpath           unicodedata
    _struct             faulthandler        pprint              unittest
    _symtable           filecmp             profile             urllib
    _testbuffer         fileinput           pstats              uu
    _testcapi           filelist            pty                 uuid
    _testconsole        fnmatch             py_compile          venv
    _testimportmultiple formatter           pyclbr              warnings
    _testmultiphase     fractions           pydoc               wave
    _thread             ftplib              pydoc_data          weakref
    _threading_local    functools           pyexpat             webbrowser
    _tkinter            gc                  pyparse             windows
    _tracemalloc        genericpath         pyshell             winreg
    _warnings           getopt              query               winsound
    _weakref            getpass             queue               wsgiref
    _weakrefset         gettext             quopri              xdrlib
    _winapi             glob                random              xml
    abc                 grep                re                  xmlrpc
    aifc                gzip                redirector          xxsubtype
    antigravity         hashlib             replace             zipapp
    argparse            heapq               reprlib             zipfile
    array               help                rlcompleter         zipimport
    ast                 help_about          rpc                 zlib
    asynchat            history             rstrip              zoomheight
    asyncio             hmac                run                 zzdummy
    asyncore            html                runpy               
    
    Enter any module name to get more help.  Or, type "modules spam" to search
    for modules whose name or summary contain the string "spam".

    --------------------------------------------------------
    1.2.导入模块方式:(模块一旦被导入,即相当于执行了另外一个py文件里的代码)
    1.
    >>> import random
    >>> random.randint(10,100)
    29
    >>> import os
    >>> os.write()
    >>> import multiprocessing

    2.
    >>> from os import rmdir
    >>> rmdir()
    >>> from os import rmdir,rename
    >>> rename()

    3.
    >>> from djano.core import handlers
    >>> from djano.core.handlers import wsgi

    4.
    >>> import multiprocessing as mul
    >>> mul.
    >>> from socket import * #全部存到dir()下 不介意这么做,名字会重名;
    >>> dir()

    --------------------------------------------------------
    1.3.导入模块路径:

    D:路飞学城练习与作业pycharm练习4.模块>python
    Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import mymodule #(模块一旦被导入,即相当于执行了另外一个py文件里的代码)
    hello alice

    >>> import mymodule 从当前目录找 找不到去sys.path下去找:
    >>> import sys
    >>> sys.path
    ['', 'C:\Users\bj\AppData\Local\Programs\Python\Python36\python36.zip', 'C:\Users\bj\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\bj\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\bj\AppData\Local\Programs\Python\Python36', 'C:\Users\bj\AppData\Local\Programs\Python\Python36\lib\site-packages']

    对于:'' 当前目录
    对于:Python36\lib\site-packages:
    内置的,第三方下载的,所有模块都会在这里

    --------------------------------------------------------
    1.4 开源模块安装使用:
    https://pypi.python.org/pypi 是python的开源模块库,(站点在美国,下载慢,容易断)(PyTyrion)(alex_sayhi)(paramiko)
    截止2017年9.30日,已经收录了118170个来自全世界python开发者贡献的模块。

    1.4.1.源码安装:(需下载)
    python setup.py build 编译源码
    python setup.py install 安装源码

    Installed c:usersjappdatalocalprogramspythonpython36libsite-packagespytyrion-1.0.1-py3.6.egg
    >>> import Tyrion
    >>> Tyrion..

    pip3 uninstall PyTyrion 卸载

    1.4.2.联网安装:
    pip3 install PyTyrion 安装联网

    c:usersjappdatalocalprogramspythonpython36libsite-packagespytyrion-1.0.1-py3.6.egg-info
    c:usersjappdatalocalprogramspythonpython36libsite-packages yrion
    >>> import Tyrion
    >>> Tyrion...

    pip3 uninstall PyTyrion 卸载

    1.4.3.国内镜像豆瓣安装:
    国内镜像豆瓣站点:如同https://pypi.python.org/pypi

    pip3 install -i http://pypi.douban.com/simple/ paramiko --trusted-host pypi.douban.com #注意simple后面得空一下

    pip install -i http://pypi.douban.com/simple/ alex_sayhi --trusted-host pypi.douban.com
    --------------------------------------------------------
    2.包(Package):对模块文件进行划分
    一个文件夹下有多个.py文件,在加上__init__.py空文件,这个文件夹就是一个包了。

    不同包之间得模块如何互相导入

    2.1.跨模块导入
    from crm import say
    入口程序得目录加载到sys.path即环境变量中,就有了跨模块得调用

    2.2.跨模块导入
    import sys,os
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(BASE_DIR)
    from proj import hello

    2.3.跨模块导入
    from . import a
    from ..proj import hello
    注意:
    python使用. .. 相对导入模块要满足两个条件:
    1.文件夹中必须有__init__.py文件,该文件可以为空,但必须要有
    2.不能作为顶层模块来执行该文件夹中得py文件(即不能作为主函数得入口)
    意思:..后不能到主函数入口得目录下

    ----------------------------------------
    总结:
    1.模块介绍
    2.导入模块方式
    3.开源模块安装
    4.包,跨模块导入

  • 相关阅读:
    Bootstrap入门(二十五)JS插件2:过渡效果
    Bootstrap入门(二十四)data属性
    Bootstrap入门(二十三)JS插件1:模态框
    Bootstrap入门(二十二)组件16:列表组
    Bootstrap入门(二十一)组件15:警告框
    Bootstrap入门(二十)组件14:警告框
    Bootstrap入门(十九)组件13:页头与缩略图
    git 上传本地代码到github 服务器
    Dropzone.js实现文件拖拽上传
    将复杂form表单序列化serialize-object.js
  • 原文地址:https://www.cnblogs.com/alice-bj/p/8465088.html
Copyright © 2020-2023  润新知