【问题标题】:How to print number of characters based on terminal width that also resize?如何根据也调整大小的终端宽度打印字符数?
【发布时间】:2017-10-23 02:23:54
【问题描述】:

不确定是否可行,但我希望做一些事情,我可以在一行上打印一个连字符来表示终端的宽度。如果窗口的宽度被调整大小,显示的连字符的数量会相应地打印出来。

【问题讨论】:

  • @khelwood 这不是重复的:这里用户还询问是否可以调整已经写好的文本的大小。
  • 如果问题已经解决,您能否告诉使用...您选择的解决方案是什么?

标签: python python-2.7


【解决方案1】:

这是一个更精细的版本,可以根据终端的尺寸始终打印您想要的任何内容。您还可以在没有打印任何内容时调整终端的大小,并且内容将相应地调整大小。

我对代码做了一些注释……但如果您需要,我可以更明确。

#!/usr/bin/env python2

import threading
import Queue
import time
import sys
import subprocess
from backports.shutil_get_terminal_size import get_terminal_size

printq = Queue.Queue()
interrupt = False
lines = []

def main():

    ptt = threading.Thread(target=printer) # Turn the printer on
    ptt.daemon = True
    ptt.start()

    # Stupid example of stuff to print
    for i in xrange(1,100):
        printq.put(' '.join([str(x) for x in range(1,i)]))           # The actual way to send stuff to the printer
        time.sleep(.5)

def split_line(line, cols):
    if len(line) > cols:
        new_line = ''
        ww = line.split()
        i = 0
        while len(new_line) <= (cols - len(ww[i]) - 1):
            new_line += ww[i] + ' '
            i += 1
            print len(new_line)
        if new_line == '':
            return (line, '')

        return (new_line, ' '.join(ww[i:]))
    else:
        return (line, '')


def printer():

    while True:
        cols, rows = get_terminal_size() # Get the terminal dimensions
        msg = '#' + '-' * (cols - 2) + '#\n' # Create the
        try:
            new_line = str(printq.get_nowait())
            if new_line != '!@#EXIT#@!': # A nice way to turn the printer
                                         # thread out gracefully
                lines.append(new_line)
                printq.task_done()
            else:
                printq.task_done()
                sys.exit()
        except Queue.Empty:
            pass

        # Build the new message to show and split too long lines
        for line in lines:
            res = line          # The following is to split lines which are
                                # longer than cols.
            while len(res) !=0:
                toprint, res = split_line(res, cols)
                msg += '\n' + toprint

        # Clear the shell and print the new output
        subprocess.check_call('clear') # Keep the shell clean
        sys.stdout.write(msg)
        sys.stdout.flush()
        time.sleep(.5)


if __name__ == '__main__':
    main()

【讨论】:

    【解决方案2】:

    这正是你所要求的......有一个非常小的问题:当你缩小外壳时,光标会下降一行,上面的东西会留在那里......我可以尝试解决这个问题……但结果会更复杂。

    我假设你使用的是 unix 系统。

    代码使用线程能够在执行其他操作时将行保持在屏幕上。在这种情况下只是休眠......而且,实际上只使用线程可以对终端尺寸的变化有一个“快速”的答案。

    #!/usr/bin/env python2
    
    import threading
    import time
    import sys
    from backports.shutil_get_terminal_size import get_terminal_size
    
    def main1():
    
        ptt = threading.Thread(target=printer2)
        ptt.daemon = True
        ptt.start()
    
        time.sleep(10)
    
    def printer2():
    
        while True:
            cols, rows = get_terminal_size()
            line = '-' * (cols - 2)
            sys.stdout.write("\r" + '#' +  line + '#')
            sys.stdout.flush()
            time.sleep(.5)
    

    【讨论】:

      【解决方案3】:

      检查一下:(它适用于 windows 和 python3)

      import os
      
      os.system('mode con: cols=100 lines=40')
      input("Press any key to continue...")
      os.system('mode con: cols=1000 lines=400')
      input("Press any key to continue...")
      

      【讨论】:

      • 以这种方式运行mode 命令只会在屏幕上显示信息,但不会捕获它。只有当它存在于当前系统上时,这种运行命令行实用程序的技术才有效。最好使用设计用于在所有/多种情况下工作的 Python 函数,而不是尝试调用特定于 Windows(或特定于 Unix)的实用程序。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多