Want to resize terminal windows in python, working but not quite right

拟墨画扇 提交于 2019-12-12 13:34:25

问题


I'm attempted to resize the terminal window on launch of a python script to ensure the display will be static size. It's working but not quite what I expected. I've tried a few methods:

import sys
sys.stdout.write("\x1b[8;40;120t")

and

import subprocess
subprocess.call(["echo","-e","\x1b[8;40;120t"])

and even just

print "\x1b[8;40;80t"

They all work and resize the real terminal. However, if my terminal is, let's say 25x80 to start, the script starts, it resizes, then exits. It will not execute the rest of the script. I wrapped it in a try/Except and nothing is thrown. Nothing in the syslogs and python -v script.py shows nothing odd. If I execute the script again or at a term size of 40x120 (my target size)..the script runs just fine. Why is exeecuting the ANSI escape exiting python? Furthermore if I run this interactively it works with no issues. Using Python 2.6.6.


回答1:


I tried to run the following script, and it "works" (Linux Debian / Python 2.6 / gnome-terminal):

print "\x1b[8;40;80t"

print "ok"

The window is resized and the script execution continue.


If you confirm in your case the program stops after resizing, my guess would be Python received a signal SIGWINCH when the window is resized.

You should try to add a specific signal handler. Something like that:

def resizeHandler(signum, frame):
    print "resize-window signal caught"

signal.signal(signal.SIGWINCH, resizeHandler)



回答2:


You need to put the terminal in cbreak mode for this. Using the term package (easy_install term) this could look like this:

from term import opentty, cbreakmode

with opentty() as tty:
    if tty is not None:
        with cbreakmode(tty, min=0):
            tty.write('\033[8;26;81t');

print 'terminal resized'


来源:https://stackoverflow.com/questions/16941885/want-to-resize-terminal-windows-in-python-working-but-not-quite-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!