Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
d4ddec59
Commit
d4ddec59
authored
Dec 03, 2011
by
Antoine Pitrou
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Refine FAQ entry for catching stdout
parent
48383bfc
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
15 additions
and
6 deletions
+15
-6
Doc/faq/extending.rst
Doc/faq/extending.rst
+15
-6
No files found.
Doc/faq/extending.rst
View file @
d4ddec59
...
...
@@ -142,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!
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment