/python3-demo/app/demo_await_object.py

https://github.com/mingz2013/study.python · Python · 136 lines · 57 code · 37 blank · 42 comment · 6 complexity · ce96ea5eb00547fd1d65d34138e057cc MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. """
  3. @FileName: demo_await_object
  4. @Time: 2020/5/29 14:42
  5. @Author: zhaojm
  6. Module Description
  7. """
  8. # 可等待对象分为三种协程任务Future
  9. import asyncio
  10. import datetime
  11. # 定义一个协程函数
  12. async def nested():
  13. return 42
  14. async def main():
  15. # Nothing happens if we just call "nested()".
  16. # A coroutine object is created but not awaited,
  17. # So it *won't run at all*.
  18. # 协程对象
  19. # a = nested()
  20. # 协程
  21. # Let's do it differently now and await it:
  22. print(await nested()) # Will print "42".
  23. async def main2():
  24. # 当一个协程通过asyncio.create_task()等函数被打包为一个任务该协程将自动排入日程准备立即运行
  25. # Schedule nested() to run soon concurrently
  26. # with "main()".
  27. task = asyncio.create_task(nested())
  28. # "task" can now be used to cancel "nested()", or
  29. # can simply be awaited to wait until it is complete.
  30. await task
  31. print(task.result())
  32. async def main3():
  33. # Future 是一种特殊的低层级可等待对象表示一个异步操作的最终结果
  34. # 当一个Future对象被等待这意味着协程将保持等待直到该Future对象在其他地方操作完毕
  35. # 在asyncio中需要Future对象以便允许通过async/await使用基于回调的代码
  36. # 通常情况下 没有必要 在应用层级的代码中创建Future对象
  37. # Future对象有时会由库和某些asyncio API暴露给用户用作可等待对象
  38. # await function_that_returns_a_future_object()
  39. # this is also valid:
  40. # await asyncio.gather(
  41. # function_that_returns_a_future_obejct(),
  42. # some_python_coroutine()
  43. # )
  44. pass
  45. def main4():
  46. # 运行asyncio程序
  47. async def main():
  48. await asyncio.sleep(1)
  49. asyncio.run(main())
  50. def main5():
  51. async def task():
  52. await asyncio.sleep(1)
  53. t = asyncio.create_task(task())
  54. def main6():
  55. async def display_date():
  56. loop = asyncio.get_event_loop()
  57. end_time = loop.time() + 5.0
  58. while True:
  59. print(datetime.datetime.now())
  60. if (loop.time() + 1.0) >= end_time:
  61. break
  62. await asyncio.sleep(1)
  63. asyncio.run(display_date())
  64. async def main7():
  65. async def factorial(name, number):
  66. f = 1
  67. for i in range(2, number + 1):
  68. print(f"Task {name}: Compute factorial({i})...")
  69. await asyncio.sleep(1)
  70. f *= i
  71. print(f"Task {name}: factorial({number}) = {f}")
  72. await asyncio.gather(
  73. factorial("A", 2),
  74. factorial("B", 3),
  75. factorial("C", 4),
  76. )
  77. async def main8():
  78. try:
  79. await asyncio.wait_for(asyncio.sleep(100), timeout=1.0)
  80. except asyncio.TimeoutError:
  81. print("timeout!")
  82. import asyncio
  83. import sys
  84. def main9():
  85. loop = asyncio.get_event_loop()
  86. loop.add_reader(
  87. sys.stdin.fileno(), lambda: print(sys.stdin.readline()))
  88. # loop.add_writer()
  89. # loop.connect_read_pipe()
  90. loop.run_forever()
  91. if __name__ == '__main__':
  92. # asyncio.run(main())
  93. # asyncio.run(main2())
  94. # main6()
  95. # asyncio.run(main7())
  96. # asyncio.run(main8())
  97. main9()