如何从 Python 调整终端 window 的大小?

How can I resize terminal window from Python?

我一直在努力尝试并将自己推向极限,但我就是不知道如何根据自己的需要调整终端的大小。有什么办法可以帮我解决吗?我希望终端在不同的操作系统中用其独特的代码来解决,或者你可以尝试用一行或多行代码来解决它。

#!usr/bin/python
# -*- coding: utf-8 -*-

### Requirements for default python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import generators

### Available for all python sources
from sys import platform
from os import system

class MainModule(object):
    def __init__(self, terminal_name, terminal_x, terminal_y):
        self.terminal_name = terminal_name
        self.terminal_x = terminal_x
        self.terminal_y = terminal_y

        if platform == "linux" or platform == "linux2":
            # Code to resize a terminal for linux distros only
        if platform == "win32" or platform == "win64":
            # Code to resize a terminal for windows only
        if platform == "darwin":
            # Code to resize a terminal for mac only

您似乎已经发现,实现是特定于平台的。您必须为每个平台编写代码来执行此操作。

在 Windows 上,有 Windows APIs that can be used to do this. You can leverage Windows APIs directly using the ctypes module. One example of this can be seen in the PyGetWindow package. Other tools like AutoHotkey (via ahk Python package), and PyWinAuto 替代工具可以为 Windows 执行此操作。

# example using the AHK package on Windows
from ahk import AHK
ahk = AHK()
win = ahk.find_window(title=b'Untitled - Notepad')
win.move(x=200, y=300, width=500, height=800)

在 MacOS 上,您可以编写 apple script 来调整 window 的大小并从子进程启动 osascript

# Using applescript on MacOS
import subprocess
APPLICATION_NAME = "Safari"
X = 300
Y = 30
WIDTH = 1200
HEIGHT = 900
APPLESCRIPT = f"""\
tell application "{APPLICATION_NAME}"
    set bounds of front window to {X}, {Y}, {WIDTH}, {HEIGHT}
end tell
"""

subprocess.run(['osascript', '-e', APPLESCRIPT], capture_output=True)

对于 Linux,正如 Jeff 在评论中提到的,Linux 实施将取决于 window 管理器使用的 there are many。但是对于像 Ubuntu 这样的流行平台,您可能会依赖现有的工具,例如 wmctrl 包或类似的包。

# ref: https://askubuntu.com/a/94866

import subprocess

WINDOW_TITLE = "Terminal"  # or substring of the window you want to resize
x = 0
y = 0
width = 100
height = 100

subprocess.run(["wmctrl", "-r", WINDOW_TITLE, "-e", f"0,{x},{y},{width},{height}"])

不过,如果您正在编写游戏或类似游戏,则可以用不同的方式解决这个问题。例如,pygame 允许您 或在基于文本的终端应用程序中,curses(或流行的 curses 包装器,blessings)可用于检测终端大小和您可以动态调整应用程序的大小,这可能需要对当前代码进行一些更改。

height = curses.LINES
width = curses.COLS

redraw(width, height) # you implement this to change how your app writes to the terminal