/asyncio/asyncio-3.4.3/examples/shell/shell.py

https://github.com/hhstore/annotated-py-flask · Python · 70 lines · 43 code · 14 blank · 13 comment · 6 complexity · ad95f4f257a492350a0f894117736b39 MD5 · raw file

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """Examples using create_subprocess_exec() and create_subprocess_shell()."""
  4. import asyncio
  5. import signal
  6. from asyncio.subprocess import PIPE
  7. #
  8. # 执行 shell 命令:
  9. #
  10. @asyncio.coroutine
  11. def cat(loop):
  12. #
  13. # 异步返回:
  14. # - 调用接口:
  15. #
  16. proc = yield from asyncio.create_subprocess_shell("cat",
  17. stdin=PIPE,
  18. stdout=PIPE)
  19. print("pid: %s" % proc.pid)
  20. message = "Hello World!"
  21. print("cat write: %r" % message)
  22. stdout, stderr = yield from proc.communicate(message.encode('ascii'))
  23. print("cat read: %r" % stdout.decode('ascii'))
  24. exitcode = yield from proc.wait()
  25. print("(exit code %s)" % exitcode)
  26. @asyncio.coroutine
  27. def ls(loop):
  28. proc = yield from asyncio.create_subprocess_exec("ls",
  29. stdout=PIPE)
  30. while True:
  31. line = yield from proc.stdout.readline()
  32. if not line:
  33. break
  34. print("ls>>", line.decode('ascii').rstrip())
  35. try:
  36. proc.send_signal(signal.SIGINT)
  37. except ProcessLookupError:
  38. pass
  39. @asyncio.coroutine
  40. def test_call(*args, timeout=None):
  41. proc = yield from asyncio.create_subprocess_exec(*args)
  42. try:
  43. exitcode = yield from asyncio.wait_for(proc.wait(), timeout)
  44. print("%s: exit code %s" % (' '.join(args), exitcode))
  45. except asyncio.TimeoutError:
  46. print("timeout! (%.1f sec)" % timeout)
  47. proc.kill()
  48. yield from proc.wait()
  49. #
  50. # 运行:
  51. #
  52. loop = asyncio.get_event_loop()
  53. loop.run_until_complete(cat(loop)) # 执行shell命令
  54. loop.run_until_complete(ls(loop)) # 执行shell命令
  55. loop.run_until_complete(test_call("bash", "-c", "sleep 3", timeout=1.0)) # 执行shell命令
  56. loop.close()