How to Redirect the Stdout into Some Sort of String Buffer

Can I redirect the stdout into some sort of string buffer?

from cStringIO import StringIO # Python3 use: from io import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

# blah blah lots of code ...

sys.stdout = old_stdout

# examine mystdout.getvalue()

Get output of a function as string

I found solution here https://stackoverflow.com/a/22434594/4204843

def f():
print('hello world')

import io
from contextlib import redirect_stdout

with io.StringIO() as buf, redirect_stdout(buf):
f()
x = buf.getvalue()

assert x == 'hello world\n'

redirect stdout/stderr to a string

Yes, you can redirect it to an std::stringstream:

std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());

std::cout << "Bla" << std::endl;

std::string text = buffer.str(); // text will now contain "Bla\n"

You can use a simple guard class to make sure the buffer is always reset:

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;
};

Redirect stdout to a string in Java

Yes - you can use a ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));

Then you can get the string with baos.toString().

To specify encoding (and not rely on the one defined by the platform), use the PrintStream(stream, autoFlush, encoding) constructor, and baos.toString(encoding)

If you want to revert back to the original stream, use:

System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));

Reroute stdout to string

Here is a way to do this using pipes and threads (which, unlike the suggested duplicate, is not limited to a predefined buffer size or risks a buffer overflow vulnerabillity):

  1. Create a pipe using std.process.pipe
  2. Set stdout to the pipe's write end (back it up first)
  3. Spawn a thread which would read from the pipe's read end and append output to a string, until the pipe is closed
  4. Execute the task at hand
  5. Close the write end of the pipe
  6. Restore the old value of stdout
  7. Wait for the thread to finish execution
  8. Use the buffer created by the thread

I have some similar code, albeit in the other direction (asynchronous writing as opposed to reading), here and here.

Redirect stdout C file stream to buffer

You can replace all printfs by myprintf where myprintf would be a function similar to fprintf but writing output to a buffer. myprintf would essentially use vsprintf to get the output into a char buffer and then to your memory buffer.

Here is a very simple and naive implementation of the concept with no error checking just to give you an idea.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

void myprintf(char *mybuffer, const char *format, ...)
{
va_list args;
va_start (args, format);

char tempbuffer[100] ;
vsprintf (tempbuffer, format, args);

strcat(mybuffer, tempbuffer) ;
va_end (args);
}

int main()
{
char buffer[100] ;
buffer[0] = 0 ;

myprintf (buffer, "Hello world!\n") ;
myprintf (buffer, "Hello %s %d", "world", 123) ;

printf (buffer) ;
return 0 ;
}

Redirect stdout to a file in Python?

If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick:

# for python3
import sys
with open('file', 'w') as sys.stdout:
print('test')

A far more common method is to use shell redirection when executing (same on Windows and Linux):

$ python3 foo.py > file

Redirect print() output into a String instead of stdout

You can try this one. If I got your question correctly.

fun index(): String {
val df_out = DataFrame.fromJson("https://jsonplaceholder.typicode.com/posts")
val outStream = ByteArrayOutputStream().apply { System.setOut(PrintStream(df_out)) }
df_out.print(maxRows = 10)
return outStream.toString()
}


Related Topics



Leave a reply



Submit