首页 > 编程语言 >Python系列(2)- Python 包 (package) 和 Pip 管理工具

Python系列(2)- Python 包 (package) 和 Pip 管理工具

时间:2022-10-25 18:12:17浏览次数:38  
标签:package Python pypi pip 模块 Pip import requests

 

1. 基本概念

    命名:

        每个变量都拥有一个名字,这个就是命名,给变量命名。变量命名也是让很多程序员头疼的一件事情,怎么样能起一些有意义,又高大上的名字。在 Python 中,一切皆对象,我们甚至可以给一个函数一个命名,命名就可以理解为所有对象的一个引用的名称。

    命名空间:

        命名空间就是用来保证命名之间不发生冲突的规则,分为:

            (1) 局部命名空间:在一个程序中为每个函数创建的命名空间,当函数执行完毕就失效;
            (2) 全局命名空间:在程序中为所有模块创建的命名空间,当程序执行完毕失效;
            (3) 内置命名空间:也就是默认的一些命名,退出程序失效;

    模块 (Module):

        在 Python 中,有三种方式创建模块:

            (1) 创建一个 Python 文件;
            (2) 用 C 语言实现,然后在运行时动态加载,比如常用的正则表达式模块 re;
            (3) 内置模块,直接 import;

    包 (package):

        包就是多个模块的集合。当项目较大,模块较多时,就可以把模块放在包中,便于管理。

        Python 的包有 Regular packages 和 Namespace packages。

        Regular packages 指目录下有__init__.py文件,并且允许嵌套,即目录下可以嵌套一个同样是 package 的子目录。Namespace packages 也是有层次结构的模块组织,不过它不必须存在于文件夹,可以存在 Zip、网络上等,且子包与父包也不必存于同一个地方。

        Python 提供的内置模块,可以直接使用 import 导入,比如 math、os、sys 等。

    import 语句:

        想使用 Python 源文件(模块),只需在另一个源文件(模块)里执行 import 语句,语法如下:

            import module

        当解释器遇到 import 语句,如果模块在当前的搜索路径就会被导入,搜索路径是一个解释器会先进行搜索的所有目录的列表。
        
        一个模块只会被导入一次,不管执行了多少次 import。

    from … import 语句:

        使用 from package import item 这种形式的时候,对应的 item 既可以是包里面的子模块(子包),也可以是模块下的函数、类或者变量。


2. Pip 管理工具

    pip 是 Python 包管理工具,该工具提供了对 Python 包的查找、下载、安装、卸载的功能。第三方包也可以在 https://pypi.org/ 中查找。

    Python 2.7.9 + 或 Python 3.4+ 以上版本都自带 pip 工具。本文使用 Windows 10 下的 Python 3.8.1 演示 pip 命令的使用方式。

        C:\>pip --version

            pip 21.3.1 from c:\applications\python-3.8.1\lib\site-packages\pip (python 3.8)

    可以使用如下命令,指定 pip 版本:
    
        C:\>python -m pip install --force-reinstall pip==19.1
    

    1) 配置 pip 源

        下载安装 python 第三方库会较慢,所以需要设置 pip 源以便快速下载,常用的国内源如下。

            阿里云                http://mirrors.aliyun.com/pypi/simple/
            中国科技大学         https://pypi.mirrors.ustc.edu.cn/simple/
            清华大学             https://pypi.tuna.tsinghua.edu.cn/simple/
            中国科学技术大学     http://pypi.mirrors.ustc.edu.cn/simple/

        命令行中使用,以 numpy 为例,在后面加 -i 源链接。

            pip install numpy -i ttp://mirrors.aliyun.com/pypi/simple/
    
        在 C:\Users\tkuang\AppData\Roaming\pip 目录下创建 pip.ini,内容如下。

            [global]
            index-url = https://mirrors.aliyun.com/pypi/simple/
                    
            [install]
            trusted-host=mirrors.aliyun.com

    2) pip 命令

        # 查看本地已安装的包
        C:\>pip list

            Package             Version
            ------------------- --------
            asgiref             3.4.1
            attrs               21.4.0
            autobahn            21.11.1
            Automat             20.2.0
            backports.zoneinfo  0.2.1
            cffi                1.15.0
            channels            3.0.4
            constantly          15.1.0
            cryptography        36.0.1
            daphne              3.0.2
            distlib             0.3.4
            Django              4.0
            filelock            3.4.2
            hyperlink           21.0.0
            idna                3.3
            incremental         21.3.0
            mod-wsgi            4.9.0
            mysqlclient         2.1.0
            numpy               1.23.3
            opencv-python       3.4.8.29
            pip                 21.3.1
            platformdirs        2.4.1
            pyasn1              0.4.8
            pyasn1-modules      0.2.8
            pycparser           2.21
            pyOpenSSL           21.0.0
            pytz                2021.3
            service-identity    21.1.0
            setuptools          41.2.0
            six                 1.16.0
            sqlparse            0.4.2
            Twisted             21.7.0
            twisted-iocpsupport 1.0.2
            txaio               21.2.1
            typing_extensions   4.0.1
            tzdata              2021.5
            virtualenv          20.11.1
            zope.interface      5.4.0


        # 安装包,但是包已经存在
        C:\>pip install numpy

            Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
            Requirement already satisfied: numpy in c:\applications\python-3.8.1\lib\site-packages (1.23.3)

        # 卸载包
        C:\>pip uninstall numpy

            Found existing installation: numpy 1.23.3
            Uninstalling numpy-1.23.3:
            Would remove:
                c:\applications\python-3.8.1\lib\site-packages\numpy-1.23.3.dist-info\*
                c:\applications\python-3.8.1\lib\site-packages\numpy\*
                c:\applications\python-3.8.1\scripts\f2py.exe
            Proceed (Y/n)? y
            Successfully uninstalled numpy-1.23.3


        # 安装包
        C:\>pip install numpy

            Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
            Collecting numpy
            Downloading https://mirrors.aliyun.com/pypi/packages/59/ec/57f87fe9dc2f8390edd1341d2ee9caa90c251f09524286476f536555ffc1/numpy-1.23.3-cp38-cp38-win_amd64.whl (14.7 MB)
                |████████████████████████████████| 14.7 MB 211 kB/s
            Installing collected packages: numpy
            Successfully installed numpy-1.23.3


        # 查看包的可安装版本
        C:\>pip install requests==

            Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
            ERROR: Could not find a version that satisfies the requirement requests== 
(from versions: 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.3.0, 0.3.1, 0.3.2, 0.3.3,
0.3.4, 0.4.0, 0.4.1, 0.5.0, 0.5.1, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.6.4, 0.6.5, 0.6.6, 
0.7.0, 0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7.5, 0.7.6, 0.8.0, 0.8.1, 0.8.2, 0.8.3, 0.8.4, 0.8.5,
0.8.6, 0.8.7, 0.8.8, 0.8.9, 0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.10.0, 0.10.1, 0.10.2, 
0.10.3, 0.10.4, 0.10.6, 0.10.7, 0.10.8, 0.11.1, 0.11.2, 0.12.0, 0.12.1, 0.13.0, 0.13.1, 0.13.2,
0.13.3, 0.13.4, 0.13.5, 0.13.6, 0.13.7, 0.13.8, 0.13.9, 0.14.0, 0.14.1, 0.14.2, 
1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.1.0, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 2.0.0, 2.0.1, 2.1.0, 2.2.0,
2.2.1, 2.3.0, 2.4.0, 2.4.1, 2.4.2, 2.4.3, 2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.6.0, 2.6.1, 
2.6.2, 2.7.0, 2.8.0, 2.8.1, 2.9.0, 2.9.1, 2.9.2, 2.10.0, 2.11.0, 2.11.1, 2.12.0, 2.12.1,
2.12.2, 2.12.3, 2.12.4, 2.12.5, 2.13.0, 2.14.0, 2.14.1, 2.14.2, 2.15.1, 2.16.0, 
2.16.1, 2.16.2, 2.16.3, 2.16.4, 2.16.5, 2.17.0, 2.17.1, 2.17.2, 2.17.3, 2.18.0, 2.18.1, 2.18.2,
2.18.3, 2.18.4, 2.19.0, 2.19.1, 2.20.0, 2.20.1, 2.21.0, 2.22.0, 2.23.0, 2.24.0, 
2.25.0, 2.25.1, 2.26.0, 2.27.0, 2.27.1, 2.28.0, 2.28.1)
            ERROR: No matching distribution found for requests==

 

3. 内置函数

    Python3 内置函数:

        abs()    dict()    help()    min()    setattr()
        all()    dir()    hex()    next()    slice()
        any()    divmod()    id()    object()    sorted()
        ascii()    enumerate()    input()    oct()    staticmethod()
        bin()    eval()    int()    open()    str()
        bool()    exec()    isinstance()    ord()    sum()
        bytearray()    filter()    issubclass()    pow()    super()
        bytes()    float()    iter()    print()    tuple()
        callable()    format()    len()    property()    type()
        chr()    frozenset()    list()    range()    vars()
        classmethod()    getattr()    locals()    repr()    zip()
        compile()    globals()    map()    reversed()    __import__()
        complex()    hasattr()    max()    round()    reload()
        delattr()    hash()    memoryview()    set()


    示例:

        C:\>python

        Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
        Type "help", "copyright", "credits" or "license" for more information.
        
        >>> print("Hello world!")
        Hello world!
        
        >>> exit()


4. 常用内置模块(包)

    1) math 模块

        math 模块是内置模块,包含许多对浮点数的数学运算函数。math 模块下的函数,返回值均为浮点数,除非另有明确说明。如果需要计算复数,请使用 cmath 模块中的同名函数。

        示例:

            >>> import math

            >>> dir(math)

            ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 
'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 
'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt',
 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 
'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'] 


    2) os 模块

        os 模块提供操作系统相关联的函数。

        示例:

            >>> import os
            >>> os.getcwd()      # 返回当前的工作目录
            'C:\\'
            >>> os.chdir('/temp')   # 修改当前的工作目录
            >>> os.system('mkdir today')   # 执行系统命令 mkdir
            0

            建议使用 "import os" 风格而非 "from os import *"。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。

    3)  glob 模块

        glob 模块提供了一个函数用于从目录通配符搜索中生成文件列表:

            >>> import glob
            >>> glob.glob('*.py')
            ['test.py', ... ]
    
    4) re 模块

        re 模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:

            >>> import re
            >>> re.findall(r'\bg[a-z]*', 'good morning, go home, get up')
            ['good', 'go', 'get']
            >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'have a nice nice day')
            'have a nice day'

        如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:

            >>> 'go up'.replace('go', 'get')
            'get up'

    5) datetime 模块

        datetime 模块为日期和时间处理同时提供了简单和复杂的方法。

        支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。

        该模块还支持时区处理:

            >>> from datetime import date
            >>> now = date.today()
            >>> now
            datetime.date(2022, 10, 24)
            >>> now.strftime("%Y-%m-%d is a %A on the %d day of %B.")
            '2022-10-24 is a Monday on the 24 day of October.'

            >>> d1 = date(1980, 1, 1)
            >>> age = now - d1
            >>> age.days
            15637


    6) zlib 模块

        以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile。

            >>> import zlib
            >>> s = b'witch which has which witches wrist watch'
            >>> len(s)
            41
            >>> t = zlib.compress(s)
            >>> len(t)
            37
            >>> zlib.decompress(t)
            b'witch which has which witches wrist watch'
            >>> zlib.crc32(s)
            226805979


    7) timeit 模块
    
        Python 提供了一个性能度量工具 timeit,可以度量不同方法之间的性能差异。

        例如,使用元组封装和拆封来交换元素相比使用传统的方法,timeit 证明了元组方法更快一些。

            >>> from timeit import Timer
            >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
            0.0191244000000097
            >>> Timer('a,b = b,a', 'a=1; b=2').timeit()
            0.015919700000040393

        相对于 timeit 的细粒度,:mod:profile 和 pstats 模块提供了针对更大代码块的时间度量工具。


5. requests 模块

    requests 模块主要用来发送 HTTP 请求,requests 模块比 urllib 模块更简洁。

    示例:

        C:\>python

        Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
        Type "help", "copyright", "credits" or "license" for more information.

        >>> import requests
        Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        ModuleNotFoundError: No module named 'requests'

        >>> exit()


        注:Python 3.8.1 下,requests 不是内置模块,需要安装。

    安装 requests 模块 (包):

        C:\>pip install requests

        Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
        Collecting requests
        Downloading https://mirrors.aliyun.com/pypi/packages/ca/91/6d9b8ccacd0412c08820f72cebaa4f0c0441b5cda699c90f618b6f8a1b42/requests-2.28.1-py3-none-any.whl (62 kB)
            |████████████████████████████████| 62 kB 1.5 MB/s
        Collecting certifi>=2017.4.17
        Downloading https://mirrors.aliyun.com/pypi/packages/1d/38/fa96a426e0c0e68aabc68e896584b83ad1eec779265a028e156ce509630e/certifi-2022.9.24-py3-none-any.whl (161 kB)
            |████████████████████████████████| 161 kB 1.3 MB/s
        Collecting urllib3<1.27,>=1.21.1
        Downloading https://mirrors.aliyun.com/pypi/packages/6f/de/5be2e3eed8426f871b170663333a0f627fc2924cc386cd41be065e7ea870/urllib3-1.26.12-py2.py3-none-any.whl (140 kB)
            |████████████████████████████████| 140 kB 1.6 MB/s
        Collecting charset-normalizer<3,>=2
        Downloading https://mirrors.aliyun.com/pypi/packages/db/51/a507c856293ab05cdc1db77ff4bc1268ddd39f29e7dc4919aa497f0adbec/charset_normalizer-2.1.1-py3-none-any.whl (39 kB)
        Requirement already satisfied: idna<4,>=2.5 in c:\applications\python-3.8.1\lib\site-packages (from requests) (3.3)
        Installing collected packages: urllib3, charset-normalizer, certifi, requests
        Successfully installed certifi-2022.9.24 charset-normalizer-2.1.1 requests-2.28.1 urllib3-1.26.12     

 

        C:\>python

        Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
        Type "help", "copyright", "credits" or "license" for more information.

        >>> import requests       
        >>> x = requests.request('get', 'https://www.baidu.com/')
        >>> print(x.status_code)
        200
        >>> exit()

 




标签:package,Python,pypi,pip,模块,Pip,import,requests
From: https://www.cnblogs.com/tkuang/p/16825815.html

相关文章

  • python 高阶函数
    概念能把函数当成参数传递的就是高阶函数一、map"""map(func,Iterable)功能:处理数据把Iterable中的数据一个一个拿出来,扔到func函数中做处理,把处理好的......
  • Python-json库
    json库python原始类型与json类型的转化对照表:PythonJSONdictobjectlist(,tuple)arrayunicode(,str)stringint(,long)number(int)float......
  • python TypeError: send_request() missing 1 required positional argument: 'self'
    问题场景:封装request的时候写了一个类,然后请求的时候接口报TypeError:send_request()missing1requiredpositionalargument:'self'首先封装的代码是这样的,如下图......
  • python内置方法
    1、abs绝对值2、round四舍五入(如果是浮点数,奇进偶不进)3、sum计算一个序列的和4、max取序列最大值5、min取序列最小值6、pow计算某个数值的x次方7、range产生......
  • python实现二叉树并且遍历
    python实现二叉树并且遍历2.1二叉树的遍历2.1.1前序遍历(根左右)二叉树的前序遍历的步骤如下:访问树的根节点---->访问当前节点的左子树---->若当前节点无左子树,访......
  • script python and python interpreter
    sPython和Python解释器https://www.cnblogs.com/nickchen121/p/10722729.html目录一、Python介绍二、Python解释器发展史三、Python解释器的类型3.1CPython3.2......
  • Python命名空间(函数)
    作用域:作用范围#命名空间:划分一块区域保存所有的数据,以字典方式存储(变量与值形成映射关系)#内建命名空间:解释器启动时创建,直到解释器运行结束,生存周期最长#全局命名空......
  • Python制作自动填写脚本,100%准确率
    本次案例代码实现思路:本次案例代码实现思路:打开考试网站selenium-->浏览器驱动-->操作浏览器<模拟人的行为做操作浏览器>获取答案获取答案网站链接获取问题......
  • Linux下 Python matplotlib 包无法使用中文
    官方办法摘抄如下#firstmethodmatplotlib.rcParams['font.family']=['SourceHanSansTW','sans-serif']#secondmethodmatplotlib.rcParams['font.family']......
  • python中的单例模式
    单例模式单例模式(singletonpattern)是一种常用的软件设计模式,主要目的是确保代码运行时,某一个类只有一个实例存在。这样可以避免多次实例化同一个类,浪费内存资源。基于......