1

Not sure if it's possible, but I was hoping to do something where I can print a hyphen for the width of the terminal on one line. If the window's width is resized, the amount of hyphens displayed would print accordingly.

3 Answers3

0

Check this out:(it worked on windows and 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...")
  • Running the `mode` command that way only displays the info on-screen, but does not capture it. That technique of shelling out to run a command-line utility only works if it is present on the current system. Better to use a Python function designed to work in all/many situations, instead trying to call a Windows-specific (or Unix-specific) utility. – MarkHu Jan 25 '21 at 22:18
0

This is doing exactly what you asked for... with a very small issue: when you make the shell smaller the cursor goes down of one line and the stuff that is above will stay there.... I can try to solve this issue... but the result will be more complicated.

I assumed you are using a unix system.

The code uses threads to be able to keep the line on the screen while doing other things. In this case just sleeping... Moreover, only using a thread is actually possible to have a "fast" answer to the change of the dimension of the terminal.

#!/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)
Riccardo Petraglia
  • 1,943
  • 1
  • 13
  • 25
0

This is a more elaborated version that allows printing whatever you want always according to the dimension of the terminal. You can also resize the terminal while nothing is being printed and the content will be resized accordingly.

I commented the code a little bit... but if you need I can be more explicit.

#!/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()
Riccardo Petraglia
  • 1,943
  • 1
  • 13
  • 25