How to get Linux console window width in Python?


In order to get the width and height of the Linux console in Python, there are different modules available that we can make use of. Two of them are the os module and the subprocess module.

In the case of the os module, we make use of the popen() method that is used to open a pipe to and from command which will help in retrieving the width and height of the Linux window.

Consider the code for the same shown below −

import os
rowSize, columnSize = os.popen('stty size', 'r').read().split()

print(rowSize)
print(colSize)

Save the above shown code in a file with a .py extension and run the following command to the terminal.

Output

immukul@192 linux-questions-code % python code.py
38
130

In the case of the subprocess module, we make use of the check_output method that will help in retrieving the width and height of the Linux window.

Consider the code for the same shown below −

import subprocess
rowSize, columnSize = subprocess.check_output(['stty', 'size']).split()
print(rowSize)
print(colSize)

Output

immukul@192 linux-questions-code % python code.py
38
130

It can be easily seen that in both the command that we are writing, whether it is the os.popen() or the subprocess.check_output() we are making use of the Linux's utility command that is stty, which is used to print the terminal line settings or simply say the characteristics of the Linux terminal, from which we will ultimately extract the height and the width.

Both the approaches will work in the latest and the old versions of Python, but it is recommended to make use of the sub process one and it is considered the future when it comes to python.

Updated on: 30-Jul-2021

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements