Reputation: 305
I'm calling a function and trying to capture the output it prints out, but in 3.3 I don't have access to StringIO. Is there another method around this?
Upvotes: 2
Views: 93
Reputation: 44634
StringIO
has moved in Python 3. Try from io import StringIO
. You also need to decide whether you want a StringIO
or a BytesIO
.
However, it sounds as though you're trying to monkey-patch over sys.stdout
in (something like) a unit test. I wouldn't recommend doing this in your tests unless you're sure you need to; it'll make for hard-to-maintain tests. I'd suggest that your code needs refactoring - consider changing your function to return a string, which clients can print (or write to a file, or display on a GUI, or...) at their leisure.
Upvotes: 0
Reputation: 387825
In Python 3, StringIO
lives in the io
package. So you can still use it to capture the output:
>>> def someMagicFunction ():
print('foo bar baz')
>>> import io, sys
>>> original = sys.stdout
>>> sys.stdout = new = io.StringIO()
>>> someMagicFunction()
>>> sys.stdout = original
>>> print(new.getvalue())
foo bar baz
Upvotes: 3
Reputation: 3459
How about setting up basic logging:
http://docs.python.org/3/library/logging.html
Here is the basic tutorial link:
http://docs.python.org/3/howto/logging.html#logging-basic-tutorial
Upvotes: 0