Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Save and restore terminal window conent using Curses for Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading