diff options
author | Antoine Pitrou <solipsis@pitrou.net> | 2011-12-03 21:40:23 (GMT) |
---|---|---|
committer | Antoine Pitrou <solipsis@pitrou.net> | 2011-12-03 21:40:23 (GMT) |
commit | 61fed9ccd3a3415d1d6fabc7cb9fad0c2a01de79 (patch) | |
tree | 63c714ed2b64e6bb600d9e158536759789aab050 /Doc/faq/extending.rst | |
parent | b6032f55d2540116b30d26a64d6a1365e27bf83b (diff) | |
parent | cc809a286a7f61a1f7605ad83a601cd2a4c10a28 (diff) | |
download | cpython-61fed9ccd3a3415d1d6fabc7cb9fad0c2a01de79.zip cpython-61fed9ccd3a3415d1d6fabc7cb9fad0c2a01de79.tar.gz cpython-61fed9ccd3a3415d1d6fabc7cb9fad0c2a01de79.tar.bz2 |
Merge from 3.2
Diffstat (limited to 'Doc/faq/extending.rst')
-rw-r--r-- | Doc/faq/extending.rst | 28 |
1 files changed, 16 insertions, 12 deletions
diff --git a/Doc/faq/extending.rst b/Doc/faq/extending.rst index 7adedf5..fa245c7 100644 --- a/Doc/faq/extending.rst +++ b/Doc/faq/extending.rst @@ -99,12 +99,7 @@ many other useful protocols. How do I use Py_BuildValue() to create a tuple of arbitrary length? ------------------------------------------------------------------- -You can't. Use ``t = PyTuple_New(n)`` instead, and fill it with objects using -``PyTuple_SetItem(t, i, o)`` -- note that this "eats" a reference count of -``o``, so you have to :c:func:`Py_INCREF` it. Lists have similar functions -``PyList_New(n)`` and ``PyList_SetItem(l, i, o)``. Note that you *must* set all -the tuple items to some value before you pass the tuple to Python code -- -``PyTuple_New(n)`` initializes them to NULL, which isn't a valid Python value. +You can't. Use :c:func:`PyTuple_Pack` instead. How do I call an object's method from C? @@ -147,21 +142,30 @@ this object to :data:`sys.stdout` and :data:`sys.stderr`. Call print_error, or just allow the standard traceback mechanism to work. Then, the output will go wherever your ``write()`` method sends it. -The easiest way to do this is to use the StringIO class in the standard library. +The easiest way to do this is to use the :class:`io.StringIO` class:: -Sample code and use for catching stdout: + >>> import io, sys + >>> sys.stdout = io.StringIO() + >>> print('foo') + >>> print('hello world!') + >>> sys.stderr.write(sys.stdout.getvalue()) + foo + hello world! + +A custom object to do the same would look like this:: - >>> class StdoutCatcher: + >>> import io, sys + >>> class StdoutCatcher(io.TextIOBase): ... def __init__(self): - ... self.data = '' + ... self.data = [] ... def write(self, stuff): - ... self.data = self.data + stuff + ... self.data.append(stuff) ... >>> import sys >>> sys.stdout = StdoutCatcher() >>> print('foo') >>> print('hello world!') - >>> sys.stderr.write(sys.stdout.data) + >>> sys.stderr.write(''.join(sys.stdout.data)) foo hello world! |