\E[?1034h escape sequence in Python output

I ran into a problem when using Biopython (although it appears to be totally unrelated to that package): writing a sequence to sys.stdout with standard output redirected to a file caused a shell escape sequence (\E[?1034h) to appear at the beginning of the resulting file, thus preventing direct use of that file in other programs.

The problem is dependent on the TERM environment variable being set to xterm; unsetting that variable, or setting it to any other value, makes the escape sequence disappear from Python’s output.

Looking into the terminfo database entry for xterm revealed the following:

$ infocmp xterm | grep 1034h
        smir=\E[4h, smkx=\E[?1h\E=, smm=\E?1034h, smso=\E[7m,

So the smm capability (Meta mode ON) seems to be the cause of the trouble. I have no idea of what this capability does (well, it turns a “meta mode” on, obviously, but I didn’t bother to search what this meta mode could be), but I will simply remove it from the terminfo entry (I’ll concede that’s quite an ugly “fix”, but I find it nicer than just unsetting TERM completely, as I have seen on some forums).

$ infocmp xterm | sed 's/, smm=[^,]\+//' > xterm
$ tic xterm
"xterm", line 2, terminal 'xterm': meta_off but no meta_on

tic(1) complains about the Meta mode OFF capability (rmm) being used without its counterpart, but apart from that, it works OK, and the escape sequence does not appear anymore.