summaryrefslogtreecommitdiffstats
path: root/Doc/library
diff options
context:
space:
mode:
authorVictor Stinner <victor.stinner@gmail.com>2014-02-03 22:26:28 (GMT)
committerVictor Stinner <victor.stinner@gmail.com>2014-02-03 22:26:28 (GMT)
commite48d4db000b600e839273d60835f2c1b80f0264f (patch)
treea8a523a2cfb963964c0d9c31c8e9f21a3931e47a /Doc/library
parentb79eb0502c5a01d4ebf793d689f6cc5fa35a1ed5 (diff)
downloadcpython-e48d4db000b600e839273d60835f2c1b80f0264f.zip
cpython-e48d4db000b600e839273d60835f2c1b80f0264f.tar.gz
cpython-e48d4db000b600e839273d60835f2c1b80f0264f.tar.bz2
asyncio doc: add an example of asyncio.subprocess with communicate() and wait()
Diffstat (limited to 'Doc/library')
-rw-r--r--Doc/library/asyncio-subprocess.rst40
1 files changed, 40 insertions, 0 deletions
diff --git a/Doc/library/asyncio-subprocess.rst b/Doc/library/asyncio-subprocess.rst
index 5bfbbc7..3d176f1 100644
--- a/Doc/library/asyncio-subprocess.rst
+++ b/Doc/library/asyncio-subprocess.rst
@@ -138,3 +138,43 @@ Process
Wait for child process to terminate. Set and return :attr:`returncode`
attribute.
+
+Example
+-------
+
+Implement a function similar to :func:`subprocess.getstatusoutput`, except that
+it does not use a shell. Get the output of the "python -m platform" command and
+display the output::
+
+ import asyncio
+ import sys
+ from asyncio import subprocess
+
+ @asyncio.coroutine
+ def getstatusoutput(*args):
+ proc = yield from asyncio.create_subprocess_exec(
+ *args,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT)
+ try:
+ stdout, _ = yield from proc.communicate()
+ except:
+ proc.kill()
+ yield from proc.wait()
+ raise
+ exitcode = yield from proc.wait()
+ return (exitcode, stdout)
+
+ loop = asyncio.get_event_loop()
+ coro = getstatusoutput(sys.executable, '-m', 'platform')
+ exitcode, stdout = loop.run_until_complete(coro)
+ if not exitcode:
+ stdout = stdout.decode('ascii').rstrip()
+ print("Platform: %s" % stdout)
+ else:
+ print("Python failed with exit code %s:" % exitcode)
+ sys.stdout.flush()
+ sys.stdout.buffer.flush()
+ sys.stdout.buffer.write(stdout)
+ sys.stdout.buffer.flush()
+ loop.close()