How to print in the middle of the screen?
Python 3 suggests shutil.get_terminal_size()
, and you can str.center
center using spaces:
import shutil
columns = shutil.get_terminal_size().columns
print("hello world".center(columns))
If you are not using Python 3 use os.get_terminal_size()
.
As @ br1ckb0t mentions, this is not convenient for Python 2. Instead of using a less convenient way, Id suggests switching to Python 3 instead.
source to share
Similarly, you did it manually: add extra spaces.
If you want to know something about display geometry, you have to go to the library for such things. for example curses
.
The curses module provides an interface to the curses library, the de facto standard for portable processing of additional terminals.
source to share
The version of get_termial_size that should work on python2 is tested but not extensively on ubuntu:
from collections import namedtuple
def get_terminal_size():
import struct
from fcntl import ioctl
from termios import TIOCGWINSZ
Res = namedtuple("terminal_sizes", field_names=["columns","lines"])
try:
term = struct.unpack('hhhh', ioctl(0, TIOCGWINSZ, '\000' * 8))
except IOError:
return Res(24, 80)
return Res(term[0], term[1])
In [23]: print("Hello world".center(get_terminal_size().columns))
Hello world
source to share