Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #100158 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2015-12-09 01:27 +1100 |
| Last post | 2015-12-09 01:27 +1100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: manually build a unittest/doctest object. Chris Angelico <rosuav@gmail.com> - 2015-12-09 01:27 +1100
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2015-12-09 01:27 +1100 |
| Subject | Re: manually build a unittest/doctest object. |
| Message-ID | <mailman.66.1449584833.12405.python-list@python.org> |
On Wed, Dec 9, 2015 at 1:04 AM, Vincent Davis <vincent@vincentdavis.net> wrote:
> I also tried something like:
> assert exec("""print('hello word')""") == 'hello word'
I'm pretty sure exec() always returns None. If you want this to work,
you would need to capture sys.stdout into a string:
import io
import contextlib
output = io.StringIO()
with contextlib.redirect_stdout(output):
exec("""print("Hello, world!")""")
assert output.getvalue() == "Hello, world!\n" # don't forget the \n
You could wrap this up into a function, if you like. Then your example
would work (modulo the \n):
def capture_output(code):
"""Execute 'code' and return its stdout"""
output = io.StringIO()
with contextlib.redirect_stdout(output):
exec(code)
return output.getvalue()
assert capture_output("""print('hello word')""") == 'hello word\n'
# no error
ChrisA
Back to top | Article view | comp.lang.python
csiph-web