There are really only two possibilities: Parse the ANSI sequences into something curses
can accept, or use the ANSI sequences as-is.
At first, the latter may seem more attractive. Most of the limitations are either irrelevant to you, or easy to deal with:
- It only works for static ANSI art, not animated files. Which is pretty reasonable, because it wouldn't make much sense to "scroll up" in an animated file. (You could of course render it on the fly to a canvas and then scroll a window up and down within that, but once you start thinking about what that rendering and windowing means… you're parsing ANSI art.) But it sounds like you only need static ANSI art.
- It only works if your terminal is (close enough to) ANSI compatible… but it is (or can be made so) or your
cat
command wouldn't work. (You may still have a problem with the color settings, but I assume you know how to work around that too.)
- It only works if your terminal is cp437, which may be more of a problem… but that's trivial to work around; just
decode('cp437')
then encode as appropriately in your code; the escape sequences are going to pass through unchanged.
- You probably want raw keyboard input. But this is as easy as
tty.setraw(sys.stdin.fileno())
and just reading stdin as an unbuffered file. (Well, you may want to stash the original tcgetattr
so you can restore it later, but that's not much harder.)
- You'll have to parse keyboard input escape sequences yourself. This is a lot of work to do generally… but just handling the up and down arrows for ANSI-art-compatible terminals is easy.
- You'll have to know how to map the ANS file to actual lines.
That last one sounds like the easy part, but it's not. For example, I grabbed a random file, GR-BANT; it's only 33 lines long, but it's got 154 newlines in it. And that's going to be pretty common. In many cases, it's just going to be "overlay lines" that start with esc-[-A, that you have to treat as part of the previous line, which is not hard to do, but there will be plenty of cases that require something more than that.
So, you're going to have to do at least some ANSI parsing, no matter what.
And once you start on that, I think you'll find an easier time with your "last resort" of doing a full parse and drawing manually to a curses pad. (And of course this has the side effects of making it possible to handle animated files, working on non-ANSI terminals, handling "keypad" keys more easily and on all terminals, …)
But if you want to go the second way, here is a quick hack that should get you started.
curses
in the first place (assuming your terminal happens to handle ANSI color, etc. sequences, that is, but you've apparently already dealt with that, given thecat
example). – Eventempered