Home > Software design >  Blocking sys.stdout and stderr does not prevent C code from printing
Blocking sys.stdout and stderr does not prevent C code from printing

Time:08-09

I am including in my python code a function compiled in c via a cython wrapper. I have to take that function as given and cannot change it. Unfortunately, when I run that function, I see output that is bothering me.

I have tried a lot of tricks that are supposed to get rid of it, all of which play with sys.stdout or sys.stderr -- most noteably, the new contextlib.redirect_stdout. However, nothing I tried managed to silence the output.

At the most basic level, I simply tried setting

    sys.stdout = open(os.devnull, 'w')
    sys.stderr = open(os.devnull, 'w')

Which is not a safe, or practicable way of doing it, but it should shut the function up. Unfortunately, I can still see the output. What am I missing? Is there perhaps another "output type" besides stdout that this function might be using?

If it helps, I am inside a Pycharm debugging session and see this output in my debugging console.

Updated question to reflect that changing stderr did not help

CodePudding user response:

Is there perhaps another "output type" besides stdout that this function might be using?

Yes, there exist stderr, which would be unaffected by stdout redirect, simple example, let printer.py content be

import sys
sys.stderr.write("printing to stderr")

then running in terminal

python printer.py > output.txt

lead to appearance of

printing to stderr

as > output.txt redirects only stdout.

CodePudding user response:

A C function prints to a file descriptor (1 for stdout, 2 for stderr). If you want to prevent the printing, redirect that FD, that can be done also temporarily. Here is a litte demo:

import os

STDOUT = 1 

saved_fd = os.dup(STDOUT)
null_fd = os.open(os.devnull, os.O_WRONLY)
os.dup2(null_fd, STDOUT)
os.system('echo TEST 1')    # redirected to /dev/null
os.dup2(saved_fd, STDOUT)
os.system('echo TEST 2')    # normal

# note: close the null_fd, saved_fd when no longer needed

If the C code opens the terminal device itself, there is very little you can do to prevent it.

  • Related