[Python-checkins] cpython: asyncio doc: add an example of asyncio.subprocess with communicate() and wait()
victor.stinner
python-checkins at python.org
Mon Feb 3 23:26:46 CET 2014
http://hg.python.org/cpython/rev/0c2f707473fc
changeset: 88949:0c2f707473fc
user: Victor Stinner <victor.stinner at gmail.com>
date: Mon Feb 03 23:26:28 2014 +0100
summary:
asyncio doc: add an example of asyncio.subprocess with communicate() and wait()
files:
Doc/library/asyncio-subprocess.rst | 40 ++++++++++++++++++
1 files changed, 40 insertions(+), 0 deletions(-)
diff --git a/Doc/library/asyncio-subprocess.rst b/Doc/library/asyncio-subprocess.rst
--- a/Doc/library/asyncio-subprocess.rst
+++ b/Doc/library/asyncio-subprocess.rst
@@ -138,3 +138,43 @@
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()
--
Repository URL: http://hg.python.org/cpython
More information about the Python-checkins
mailing list