Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does my embedded python stdout go?

Consider the following MWE:

#include <Python.h>
#include <stdio.h>

int main(void) {
  printf("Test 1\n");
  Py_Initialize();
  printf("Test 2\n");
  PyRun_SimpleString("print('Test 3')");
  printf("Test 4\n");
  return 0;
}

When I compile and run this as normal i get the expected output:

$ ./test
Test 1
Test 2
Test 3
Test 4

But when I redirect the output I get nothing from the python code:

$ ./test | cat
Test 1
Test 2
Test 4

What is happening? And more importantly how do I get my python output written to stdout like expected?

like image 521
A. Nilsson Avatar asked Jun 30 '15 09:06

A. Nilsson


People also ask

Does python print go to stdout?

print() and Standard Out. Every running program has a text output area called "standard out", or sometimes just "stdout". The Python print() function takes in python data such as ints and strings, and prints those values to standard out.

How do you find the standard output in Python?

A built-in file object that is analogous to the interpreter's standard output stream in Python. stdout is used to display output directly to the screen console. Output can be of any form, it can be output from a print statement, an expression statement, and even a prompt direct for input.

What is SYS __ stdout __?

In IDLE, sys. __stdout__ is the program's original standard output - which goes nowhere, since it's not a console application. In other words, IDLE itself has already replaced sys. stdout with something else (its own console window), so you're taking two steps backwards by replacing your own stdout with __stdout__ .


1 Answers

When stdout refers to a terminal, the output is line buffered otherwise which is block or fully buffered, won't output until the block is full.

To make the output line buffered when stdout refers to non-terminal, set the mode with setvbuf
And you have to call Py_Finalize() to have libpython close its I/O handle.

#include <Python.h>
#include <stdio.h>

int
main(int argc, char **argv) {
    //setlinebuf(stdout);
    setvbuf(stdout, NULL, _IOLBF, 0);
    printf("Test 1\n");
    Py_Initialize();
    printf("Test 2\n");
    PyRun_SimpleString("print('Test 3')");
    Py_Finalize();
    printf("Test 4\n");
    return 0;
}
like image 79
Nizam Mohamed Avatar answered Sep 20 '22 02:09

Nizam Mohamed