]> granicus.if.org Git - python/commitdiff
asyncio doc: add an example of asyncio.subprocess with communicate() and wait()
authorVictor Stinner <victor.stinner@gmail.com>
Mon, 3 Feb 2014 22:26:28 +0000 (23:26 +0100)
committerVictor Stinner <victor.stinner@gmail.com>
Mon, 3 Feb 2014 22:26:28 +0000 (23:26 +0100)
Doc/library/asyncio-subprocess.rst

index 5bfbbc7459ff0b0005b973f275cbe49bdd4f9db0..3d176f100dff1a328c258acf6dfe378cf6e60d74 100644 (file)
@@ -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()