Skip to content

Instantly share code, notes, and snippets.

@Liudx1985
Created September 22, 2015 07:15
Show Gist options
  • Save Liudx1985/749cf30de0f33316799c to your computer and use it in GitHub Desktop.
Save Liudx1985/749cf30de0f33316799c to your computer and use it in GitHub Desktop.
from io import StringIO
import sys
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
# blah blah lots of code ...
print("fuck me god")
sys.stdout = old_stdout
content = mystdout.getvalue()
print (content)
mystdout.close()
// Redirect_io_string
struct cout_redirect {
cout_redirect(std::streambuf * new_buffer)
: old(std::cout.rdbuf(new_buffer))
{ }
~cout_redirect() {
std::cout.rdbuf(old);
}
private:
std::streambuf * old;
};
int main(){
std::cout << "Fuck me god\n";
std::string text;
text.resize(64);
{
std::stringstream buffer;
cout_redirect cd(buffer.rdbuf());
std::cout << "Bla" << std::endl;
text = buffer.str(); // text will now contain "Bla\n"
}
std::cout << text << std::endl;
//
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment