How do you suppress output in Jupyter running IPython? - jupyter-notebook

How can output to stdout be suppressed?
A semi-colon can be used to supress display of returned objects, for example
>>> 1+1
2
>>> 1+1; # No output!
However, a function that prints to stdout is not affected by the semi-colon.
>>> print('Hello!')
Hello!
>>> MyFunction()
Calculating values...
How can the output from print / MyFunction be suppressed?

Add %%capture as the first line of the cell. eg
%%capture
print('Hello')
MyFunction()
This simply discards the output, but the %%capture magic can be used to save the output to a variable - consult the docs

Suppress output
Put a ; at the end of a line to suppress the printing of output [Reference].
A good practice is to always return values from functions rather than printing values inside a function. In that case, you have the control; if you want to print the returned value, you can; otherwise, it will not be printed just by adding a ; after the function call.

(credit: https://stackoverflow.com/a/23611571/389812)
You could use io.capture_output:
from IPython.utils import io
with io.capture_output() as captured:
MyFunction()
to supress (e.g. capture) stdout and stderr for those lines within the with-statement.

If anyone is interested in clearing all outputs:
Go to Cell
Go to All Output
Then choose whichever option you like.

Related

Variable output in Pluto Notebook

I'm in the process of working on a coding project in a pluto notebook. It's early days but I'm curious why the value of 1000 doesn't show beside quadorder in the screenshot above. It seems to output for everything else!
It is the ; in your code that triggers that. However, I don't think it is supposed to be expected behavior. It is supposed to be a comment, but the parser probably sees the ; and thinks that it is part of the code.
If you put it between quoting marks then this doesn't happen.
I.e. this should work as expected:
quadorder = 1000 # like python Julia doesn't require ';'
Otherwise, it would usually also work if you just don't put it at the end of the line.
The Julia REPL evaluates the semicolon wrongly and it is a know issue github.com/JuliaLang/julia/issues/28743.
You can actually trick it into some weird behavior that suppresses output. For example this returns no output:
julia> ";#"
julia> a = ["; #", "hi", 3]
julia> a = "223" #;
The reason is that the REPL parser looks for the last semicolon in the line and if there is any # or if it is at the end of the line (whitespaces don't matter), then it suppresses any output.

Julia print statement not working in certain cases

I've written a prime-generating function generatePrimes (full code here) that takes input bound::Int64 and returns a Vector{Int64} of all primes up to bound. After the function definition, I have the following code:
println("Generating primes...")
println("Last prime: ", generatePrimes(10^7)[end])
println("Primes generated.")
which prints, unexpectedly,
Generating primes...
9999991
Primes generated.
This output misses the "Last prime: " segment of the second print statement. The output does work as expected for smaller inputs; any input at least up to 10^6, but somehow fails for 10^7. I've tried several workarounds for this (e.g. assigning the returned value or converting it to a string before calling it in a print statement, combining the print statements, et cetera) and discovered some other weird behaviour: if the "Last prime", is removed from the second print statement, for input 10^7, the last prime doesn't print at all and all I get is a blank line between the first and third print statements. These issues are probably related, and I can't seem to find anything online about why some print statements wouldn't work in Julia.
Thanks so much for any clarification!
Edit: Per DNF's suggestion, following are some reductions to this issue:
Removing the first and last print statements doesn't change anything -- a blank line is always printed in the case I outlined and each of the cases below.
println(generatePrimes(10^7)[end]) # output: empty line
Calling the function and storing the last index in a variable before calling println doesn't change anything either; the cases below work exactly the same either way.
lastPrime::Int = generatePrimes(10^7)[end]
println(lastPrime) # output: empty line
If I call the function in whatever form immediately before a println, an empty line is printed regardless of what's inside the println.
lastPrime::Int = generatePrimes(10^7)[end]
println("This doesn't print") # output: empty line
println("This does print") # output: This does print
If I call the function (or print the pre-generated-and-stored function result) inside a println, anything before the function call (that's also inside the println) isn't printed. The 9999991 and anything else there may be after the function call is printed only if there is something else inside the println before the function call.
# Example 1
println(generatePrimes(10^7)[end]) # output: empty line
# Example 2
println("This first part doesn't print", generatePrimes(10^7)[end]) # output: 9999991
# Example 3
println("This first part doesn't print", generatePrimes(10^7)[end], " prints") # output: 9999991 prints
# Example 4
println(generatePrimes(10^7)[end], "prime doesn't print") # output: prime doesn't print
I could probably list twenty different variations of this same thing, but that probably wouldn't make things any clearer. In every single case version of this issue I've seen so far, the issue only manifests if there's that function call somewhere; println prints large integers just fine. That said, please let me know if anyone feels like they need more info. Thanks so much!
Most likely you are running this code from Atom Juno which recently has some issues with buffering standard output (already reported by others and I also sometimes have this problem).
One thing you can try to do is to flush your standard output
flush(stdout)
Like with any unstable bug restarting Atom Juno also seems to help.
I had the same issue. For me, changing the terminal renderer (File -> Settings -> Packages -> julia-client -> Terminal Options) from webgl to canvas (see pic below) seems to solve the issue.
change terminal renderer
I've also encountered this problem many times. (First time, it was triggered after using the debugger. It is probably unrelated but I have been using Julia+Juno for 2 weeks prior to this issue.)
In my case, the code before the println statement needed to have multiple dictionary assignation (with new keys) in order to trigger the behavior.
I also confirmed that the same code ran in Command Prompt (with same Julia interpreter) prints fine. Any hints about how to further investigate this will be appreciated.
I temporarily solve this issue by printing to stderr, thinking that this stream has more stringent flush mechanism: println(stderr, "hello!")

When defined in a script, Julia functions don't print output

I have this Julia script:
function f(x,y)
x+y
end
f(3, 4)
When I run this in the live terminal (via copy/paste), I get the desired result 7. But if I run the script, the output from the function is suppressed. Why is that?
Julia, unlike Matlab, doesn't automatically print values (the REPL does since that's what it's for: REPL = "read, eval, print loop"). You have to explicitly print the value using print or show, e.g. show(f(3, 4)). In this case, print and show do the same thing, but in general they have somewhat different meanings:
print([io::IO], xs...)
Write to io (or to the default output stream stdout if io is not given) a canonical (un-decorated) text representation. The representation used by print includes minimal formatting and tries to avoid Julia-specific details.
versus
show(x)
Write an informative text representation of a value to the current output stream. New types should overload show(io::IO, x) where the first argument is a stream. The representation used by show generally includes Julia-specific formatting and type information.
Note that there is also the #show macro, which prints the expression that is evaluated followed by its value, like so:
julia> #show f(3, 4);
f(3, 4) = 7

Why does sourcing a script not print out to stdout?

In a R session, I source a simple r script whose content is:
x = c(1,2)
x
as
source('my.r')
I wonder why running it in the R session doesn't show any output?
(I find that I can use print() to show the value of x.)
Thanks.
It is the way source is configured. You can change it with the options echo and print.eval:
echo logical; if TRUE, each expression is printed after parsing,
before evaluation.
print.eval logical; if TRUE, the result of
eval(i) is printed for each expression i; defaults to the value of
echo.
So try source("my.r", print.eval=TRUE)
So far as I understand it, when you run source, you are starting a separate environment inside which source is executing, just like any other function. As such, x "prints" the value of x inside that environment, but the console is one environment "up" the chain.
Try, for example,
foo<-function(x) {
x
return(4)
}
EDIT: James has more directly answered the "how" part of your question.

Run a function without executing its print() statements

I wrote a function that outputs a single element numeric after a 300-cycle for loop. I make it print about 10 lines in each cycle, to know where it's at. Now I want to run this for loop itself in a 1000 cycle for loop (and place the resulting numbers in a matrix). But it prints way to much stuff and I don't know where it's at in the execution of the outer (1000 cycle) for loop. The output from the inner for loop overwhelms a print statement executed at each of the outer loop's cycles. Here's how it looks:
for(i in 1:1000){
function(...){...} #prints 10 lines 300 times before outputting a single element numeric
cat("Outer loop step "); print(i)}
Now I don't want to remove the print statements from my function, but I want to mute them when I call the function in that for loop. How can I run my function without executing it's print() statements?
Modify your function so you can pass in a "debug" true/false parameter to control the print statements.
Don't use print or cat. Use message instead. You can then use suppressMessages to suppress the message output.

Resources