ThePortakal
ThePortakal

Reputation: 239

Clear output only printed by function

Consider the following script:

from IPython.display import clear_output
import time

def func1():
    print('Func1 started.')
    time.sleep(1)
    clear_output()
    print('Func1 step1 completed.')
    time.sleep(1)
    clear_output()
    print('Func1 step2 completed.')
    time.sleep(1)
    clear_output()
    print('Func1 completed.')
    
def func2():
    print('Func2 started.')
    time.sleep(1)
    clear_output()
    print('Func2 step1 completed.')
    time.sleep(1)
    clear_output()
    print('Func2 step2 completed.')
    time.sleep(1)
    clear_output()
    print('Func2 completed.')

func1()
func2()

When I am running func2, the final output printed by func1 gets deleted. Is there a way to keep "Func1 completed." printed when running func2?

Upvotes: 0

Views: 246

Answers (1)

jDimmy
jDimmy

Reputation: 21

You can display in two differents outputs :

from IPython.display import clear_output, display
from ipywidgets import Output
import time

def func1():
    print('Func1 started.')
    time.sleep(1)
    clear_output()
    print('Func1 step1 completed.')
    time.sleep(1)
    clear_output()
    print('Func1 step2 completed.')
    time.sleep(1)
    clear_output()
    print('Func1 completed.')
    
def func2():
    print('Func2 started.')
    time.sleep(1)
    clear_output()
    print('Func2 step1 completed.')
    time.sleep(1)
    clear_output()
    print('Func2 step2 completed.')
    time.sleep(1)
    clear_output()
    print('Func2 completed.')


out1 = Output()
out2 = Output()

display(out1)
with out1:
    func1()
display(out2)
with out2:
    func2()

The outputs of the two functions will be displayed.

Upvotes: 1

Related Questions