I’m making some console app on Python with Curses (window-curses) library. At some point I need to save window state (or maybe whole terminal state) to some object/variable and restore it in future.
What’s the proper way to do this?
I found methods in module documentaion which do this via saving state to the file. But maybe there exists some other way to do this in memory.
>Solution :
As you found, you can use things like the putwin function to save a pad to a file and getwin to restore it from a file. If you want to keep this in memory, rather than a file on disk, you can use a BytesIO object in place of a real file handle.
import io
import curses
curses.initscr()
pad = curses.newpad(100, 100)
# ... do things with the pad
# save the pad in memory
f = io.BytesIO()
pad.putwin(f)
# later recall the data
f.seek(0) # reset the cursor to the beginning of the "file"
pad.getwin(f)
You could also write some functions to describe this another way:
def save_win(win) -> bytes:
f = io.BytesIO()
win.putwin(f)
bytes_data = f.getvalue()
return bytes_data
def load_win(bytes_data: bytes) -> curses.window:
f = io.BytesIO(bytes_data)
f.seek(0)
return curses.getwin(f)