Suppress Output of a Function

Suppress output of a function

It isn't clear why you want to do this without sink, but you can wrap any commands in the invisible() function and it will suppress the output. For instance:

1:10 # prints output
invisible(1:10) # hides it

Otherwise, you can always combine things into one line with a semicolon and parentheses:

{ sink("/dev/null"); ....; sink(); }

It's possible suppress output about of one function?

Using only standard C++ where no dup-like functions exist, you could open a temporary std::FILE and std::swap with stdout.

#include <cerrno>
#include <cstring>
#include <cstdio>

#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>

// extern "C" int function(); // an assumption

// A helper class to temporarilly redirect the output to stdout to a file and to read
// the content of the file afterwards.

class BufferStdout {
public:
// the collector string is used for collecting the output to stdout
BufferStdout (std::string& collector) :
m_collector(collector),
fp(std::fopen("output.txt", "w"))
{
if(fp == nullptr) throw std::runtime_error(std::strerror(errno));
std::swap(stdout, fp); // swap stdout and the temp file
}

~BufferStdout () {
std::swap(stdout, fp); // swap back
std::fclose(fp);

// read the content of the temp file into m_collector
if(std::ifstream is("output.txt"); is) {
m_collector.append(std::istreambuf_iterator<char>(is),
std::istreambuf_iterator<char>{});
}
std::remove("output.txt"); // cleanup
}

private:
std::string& m_collector;
std::FILE* fp;
};

int main() {
std::string collector; // the string that will contain the output from function()
int a;
{
BufferStdout foo(collector);
a = function();
}
std::cout << "the result is : " << a << '\n';
std::cout << "Collected from function():\n";
std::cout << collector << '\n';
}

Suppress automatic output to console in R

The issue is due to the fact that the function has multiple print statements, where stop, warning, or message would have been appropriate so that people can use suppressWarnings or suppressMessages.

You can work arount it using invisible(capture.output()) around your whole assignment (not just the right side).


f1 <- function(n, ...){
print("Random print statement")
cat("Random cat statement\n")
rnorm(n = n, ...)
}

f1(2)
#> [1] "Random print statement"
#> Random cat statement
#> [1] -0.1115004 -1.0830523
invisible(capture.output(x <- f1(2)))
x
#> [1] 0.0464493 -0.1453540

See also suppress messages displayed by "print" instead of "message" or "warning" in R.

Is there a way to suppress outputs inside a function in a Julia Jupyter notebook?

As phyatt's answer highlights it would often be better for library code to use a configurable logging mechanism. However, sometimes you want to call code that, for whatever reason, writes directly to stdout. One way to handle these cases is to use redirect_stdout.

For example:

real_stdout = stdout
(rd, wr) = redirect_stdout();
# Noisy code here
redirect_stdout(real_stdout)

You'd probably want to put this in a function or a macro or simply use Suppressor.jl a library that provides these macros. If you want to capture the output the way the ipython %%capture magic does you can have a look at @capture_out in Suppressor.jl, this SO question and this forum thread.

How to suppress function output in python

Yes, yes you can do something like that. Exactly that, actually.

Assign the argument you want to ignore to a name you then simply not use anywhere else. The _ name is often used:

_, arg2 = myFunction(arg1, arg2)

The _ name is just a convention, but most Python developers understand it to mean 'this variable will be ignored by the rest of the code, it is just there to fulfill a tuple assignment'.

Alternatively, index or slice the output:

arg2 = myFunction(arg1, arg2)[-1]

or for a function with more than two return values:

arg2, arg3 = returnsMoreThanTwo(arg1, arg2)[-2:]

but if you wanted to ignore an argument in the middle somewhere, the _ assignment is best. You can use it multiple times without penalty:

arg1, _, _, arg4 = returnsFourArguments(arg1, arg2)

Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call

Assigning the stdout variable as you're doing has no effect whatsoever, assuming foo contains print statements -- yet another example of why you should never import stuff from inside a module (as you're doing here), but always a module as a whole (then use qualified names). The copy is irrelevant, by the way. The correct equivalent of your snippet is:

import sys
save_stdout = sys.stdout
sys.stdout = open('trash', 'w')
foo()
sys.stdout = save_stdout

Now, when the code is correct, is the time to make it more elegant or fast. For example, you could use an in-memory file-like object instead of file 'trash':

import sys
import io
save_stdout = sys.stdout
sys.stdout = io.BytesIO()
foo()
sys.stdout = save_stdout

for elegance, a context is best, e.g:

import contextlib
import io
import sys

@contextlib.contextmanager
def nostdout():
save_stdout = sys.stdout
sys.stdout = io.BytesIO()
yield
sys.stdout = save_stdout

once you have defined this context, for any block in which you don't want a stdout,

with nostdout():
foo()

More optimization: you just need to replace sys.stdout with an object that has a no-op write method. For example:

import contextlib
import sys

class DummyFile(object):
def write(self, x): pass

@contextlib.contextmanager
def nostdout():
save_stdout = sys.stdout
sys.stdout = DummyFile()
yield
sys.stdout = save_stdout

to be used the same way as the previous implementation of nostdout. I don't think it gets any cleaner or faster than this;-).



Related Topics



Leave a reply



Submit