如何为终端应用程序编写透明包装器?

问题描述 投票:0回答:1

包装器应该处理特殊控制字符并执行某些操作,但不会干扰实际应用程序。 (尝试构建像app这样的tmux)

到目前为止,我在doc:https://docs.python.org/3/library/pty.html#example中有以下修改示例

import pty
import os

def handle_special_cmd(data):
    # TODO
    raise NotImplementedError

def inread(fd):
    data = os.read(fd, 1024)
    if b'\x02' in data: # ctrl B
        return handle_special_cmd(data)
    return data

def main():
    cmd="vim"
    pty.spawn(cmd, stdin_read=inread)

if __name__=='__main__':
    main()

上面的代码有效但vim打开并没有覆盖整个终端窗口。它以减少的行和列bad vim开始vim

如果我只是从shell中键入vim它可以正常工作:good vim

为什么会发生这种情况以及如何解决?我的目标不仅仅是修复行和列,但包装器应该是真正透明的,除了捕获特殊的ctrl字符并做一些事情。无论当前shell有什么tty / colors和其他设置都应该传递给实际的可执行文件。它应该像我输入vim一样工作。 (Linux特定的解决方案很好。不需要在所有posix中工作。如果需要c扩展也没问题)。

python linux console tty pty
1个回答
1
投票

窗口大小唯一地是PTY本身的属性。您可以使用TIOCGWINSZTIOCSWINSZ ioctls获取和设置它:

import sys, fcntl, termios, struct

buf = bytearray(4)
fcntl.ioctl(sys.stdin.fileno(), termios.TIOCGWINSZ, buf)
(h, w) = struct.unpack("HH", buf)
print("Terminal is {w} x {h}".format(w=w, h=h))

[...]

fcntl.ioctl(child_pty.fileno(), termios.TIOCSWINSZ, struct.pack("HH", h, w))
© www.soinside.com 2019 - 2024. All rights reserved.