在整个屏幕宽度上打印短划线

2024-04-28 21:16:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望打印一个破折号"-"直到用户的屏幕结束。在

基本上,我的程序会打印一行文本,然后在下面打印一行破折号,然后再打印另一行文本。这样做的目的是让用户可以很容易地区分第一行和第二行。在

像这样:

First line of text
--------------------------------------------------------------------------------------
Second line of text

我有没有办法使用标准的Python2.6库来实现这一点。我不能使用任何其他库,如texttable或更新版本的Python。在


Tags: oftext用户文本程序目的标准屏幕
1条回答
网友
1楼 · 发布于 2024-04-28 21:16:19

2.6?好吧,那已经很老了。 这应该是有效的: (取自How to get Linux console window width in Python

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

(width, height) = getTerminalSize()

print "-" * width

相关问题 更多 >