Force redraw() / redraw with callback

I have a p5py application that requires getting data from the internet on user input. I’m running the sketch with no_loop() in the setup as animation is only required on user input.

Fetching and processing the data can take a second, but the user input is available immediately and I would like to draw it to the screen right away, then do the fetching and processing.

The following code is inside of key_pressed(), which keeps track of user input in the object user_input

    if key == 'ENTER':
        # assign the global variable text_to_display to whatever the user typed
        text_to_display = user_input
        # call draw to render that text to screen
        # get and process data from the input

I would expect redraw to execute before get_and_process is called, but that’s not happening. I see the redrawn results only after get_and_process is complete.

Maybe something analogous to p5’s request animation frame step is happening. Is there a way for me to force redraw to execute before the program moves on? Or to call get_and_process as a callback on redraw()?

Disclaimer: I know nothing about async techniques and threads in Python.

It seems that the entire key_pressed() block must complete before the next frame can redraw. Maybe you could use a thread? Something like –

from p5 import *
import threading

def setup():
    size(500, 500)

def draw():
    text(str(frame_count), 10, 10)

def key_pressed(e):
    worker = threading.Thread(target=print_frame_count)

def print_frame_count():


The frame number is drawn in the display window two seconds before it appears in the console.


That did the trick. Thanks a bunch!