查看Python中的关键字

    import keyword

    print(keyword.kwlist)  # 返回一个包含Python关键字的列表
    """执行结果
        ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
        'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
        'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
        'return', 'try', 'while', 'with', 'yield']
    """

1.False

    布尔类型的值,表示假
    None    空字符串    空元祖     空列表     空字典     空集合     0  # 真值都是False
    None    str()           tuple()     list()       dict()       set()       int()  # 真值都是False
    None    ""               ()             []             {}           set()        0  # 真值都是False

2.None

    None是一个特殊的常量,None和False不同,None不是0,None不是空字符串
    None和任何其他数据类型比较永远返回False,None有自己的数据类型NoneType,None可以赋值给任何变量,但是不能创建其他NoneType对象
    示例:
        In [13]: type(None)
        Out[13]: NoneType

        In [14]: None == 0
        Out[14]: False

        In [15]: None == ""
        Out[15]: False

        In [16]: None == None
        Out[16]: True

        In [17]: None == False
        Out[17]: False

3.True

    布尔类型的值,表示真,与False相反
    非0为真

4.and

    逻辑判断语句,and左右两边都为真,则判断结果为真,否则都是假
    示例:
        # 左边为真时,返回右边的值
        1 and 5  # 5
        # 左边为假时, 返回左边的值
        0 and 5  # 0

5.as

    常结合with使用,常用于打开文件操作,也用于在导入模块时给模块起别名
    示例:
        import multiprocessing as muti

        with open("文件路径", "w") as f:
            f.write("hello world!")

6.assert

    断言,用来在运行中检查程序的正确性,和其他语言一样的作用
    示例:
        mylist = []
        assert len(mylist) >= 1 # 抛出异常 AssertionError
        print("继续执行")

7.asymc 和 await

    async:
        修饰将普通函数和生成器函数包装成异步函数和异步生成器
        异步函数的特点是能在函数执行过程中挂起,去执行其他异步函数,等到挂起条件假设挂起条件是 sleep(5),也就是5秒到了再回来执行
    await:
        1.用来用来声明程序挂起,比如异步程序执行到某一步时需要等待的时间很长,就将此挂起去执行其他的异步程序
        2.await 后面只能跟异步程序或有__await__属性的对象,因为异步程序与一般程序不同
            假设有两个异步函数async a 和 async b
            a中的某一步有 await,当程序碰到关键字 await b()后,异步程序挂起后去执行另一个异步b程序,即从函数内部跳出去执行其他函数
            当挂起条件消失后,不管b是否执行完,要马上从b程序中跳出来,回到原程序执行原来的操作
            如果 await 后面跟的b函数不是异步函数,那么操作就只能等b执行完再返回,无法在b执行的过程中返回
            如果要在b执行完才返回,也就不需要用 await 关键字了,直接调用b函数就行
            所以这就需要await后面跟的是异步函数了,在一个异步函数中,可以不止一次挂起,也就是可以用多个 await

from time import sleep
from time import time


def demo1():
    """demo1方案
        假设我们有三台洗衣机,现在有三批衣服需要分别放到这三台洗衣机里面洗
        运行demo1(),那么需要10秒钟才能把全部衣服洗完,大部分时间都花在挨个地等洗衣机上了
    """
    
    def washing1():
        sleep(3)  # 第一台洗衣机,需要洗3秒才能洗完
        print('washer1 finished')  # 洗完的时候,通过打印告知
    
    def washing2():
        sleep(2)  # 第二台洗衣机,需要洗3秒才能洗完
        print('washer2 finished')
    
    def washing3():
        sleep(5)  # 第三台洗衣机,需要洗3秒才能洗完
        print('washer3 finished')
    
    washing1()
    washing2()
    washing3()


def demo2():
    """demo2方案
        现在我们想要避免无谓的等待,为了提高效率,我们将使用 async
        washing1/2/3()本是普通函数,现在我们用async把它们升级为异步函数
        注: 一个异步的函数,有个更标准的称呼,我们叫它"协程"(coroutine)
    """
    
    async def washing1():
        sleep(3)
        print('washer1 finished')
    
    async def washing2():
        sleep(2)
        print('washer2 finished')
    
    async def washing3():
        sleep(5)
        print('washer3 finished')
    
    washing1()
    washing2()
    washing3()
    """打个比方便于理解demo2
        从正常人的理解来看,我们现在有了异步函数,但是却忘了定义应该什么时候"离开"一台洗衣
        机,去看看另一个洗衣机,这就会导致,我们一边看着第一台洗衣机,一边想着是不是该去开第二台洗衣机
        但又不敢去,最终还是花了10秒的时间才把衣服洗完
        PS: 其实 demo2() 是无法运行的,Python 会直接警告:
            RuntimeWarning: coroutine 'demo2.<locals>.washing1' was never awaited
            RuntimeWarning: coroutine 'demo2.<locals>.washing2' was never awaited
            RuntimeWarning: coroutine 'demo2.<locals>.washing3' was never awaited
    """


def demo3():
    """demo方案
        吸取了demo2的教训,告诉自己洗衣服的过程是"可等待的"(awaitable)
        在开启第一台洗衣机洗衣服的时候,我们可以去开别的洗衣机
    """
    
    async def washing1():
        await sleep(3)  # 注意这里加入了 await
        print('washer1 finished')
    
    async def washing2():
        await sleep(2)
        print('washer2 finished')
    
    async def washing3():
        await sleep(5)
        print('washer3 finished')
    
    washing1()
    washing2()
    washing3()
    """demo3方案
        尝试运行一下,我们会发现还是会报错(报错内容和demo2一样),报错原因分析如下
        1.第一个问题是, await 后面必须跟一个 awaitable 类型或者具有 __await__ 属性的对象
            这个 awaitable, 并不是我们认为 sleep() 是 awaitable 就可以 await 了
            常见的 awaitable 对象应该是: await asyncio.sleep(3)
            asyncio 库的 sleep() 机制与 time.sleep() 不同,前者是"假性睡眠",后者是会导致线程阻塞的"真性睡眠"
            await an_async_function()  # 一个异步的函数,也是可等待的对象
            以下是不可等待的示例验证:
                await time.sleep(3)
                x = await 'hello'  # <class 'str'> doesn't define '__await__'
                x = await 3 + 2  # <class 'int'> dosen't define '__await__'
                x = await None  # ...
                x = await a_sync_function()  # 普通的函数,是不可等待的
        2.第二个问题是,如果我们要执行异步函数,不能用这样的调用方法:
            washing1()
            washing2()
            washing3()
        而应该用 asyncio 库中的事件循环机制来启动,具体见 demo4 的最终方案
    """


def demo4():
    """demo4方案
        这是最终我们想要的实现
    """
    import asyncio  # 引入 asyncio 库
    
    async def washing1():
        await asyncio.sleep(3)  # 使用 asyncio.sleep() 它返回的是一个可等待的对象
        print('washer1 finished')
    
    async def washing2():
        await asyncio.sleep(2)
        print('washer2 finished')
    
    async def washing3():
        await asyncio.sleep(5)
        print('washer3 finished')
    
    """事件循环机制分为以下几步骤
        1.创建一个事件循环
        2.将异步函数加入事件队列
        3.执行事件队列,直到最晚的一个事件被处理完毕后结束
        4.最后建议用 close() 方法关闭事件循环,以彻底清理 loop 对象防止误用
    """
    # 1.创建一个事件循环
    loop = asyncio.get_event_loop()
    
    # 2.将异步函数加入事件队列
    tasks = [
        washing1(),
        washing2(),
        washing3(),
    ]
    
    # 3.执行事件队列,直到最晚的一个事件被处理完毕后结束
    loop.run_until_complete(asyncio.wait(tasks))

    # # 执行事件队列也可以这样写,运行的效果是一样的
    # tasks = [
    #     loop.create_task(washing1()),
    #     loop.create_task(washing2()),
    #     loop.create_task(washing3()),
    # ]

    # 4.如果不再使用 loop,则调用 close关闭事件循环,类似于文件读写结束时的 close() 操作
    loop.close()
    """最终的打印效果
        washer2 finished
        washer1 finished
        washer3 finished
        elapsed time = 5.126561641693115
    """


if __name__ == '__main__':
    start = time()  # 为验证是否真的缩短了时间,做一下记时
    
    # demo1()  # 需花费10秒
    # demo2()  # 会报错: RuntimeWarning: coroutine ... was never awaited
    # demo3()  # 会报错: RuntimeWarning: coroutine ... was never awaited
    demo4()  # 需花费5秒多一点点
    
    end = time()
    print('elapsed time = ' + str(end - start))
示例说明:

相关文章: