Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Using os.popen() Method
Consider the code for the same shown below −
import os
rowSize, columnSize = os.popen('stty size', 'r').read().split()
print(rowSize)
print(columnSize)
Save the above shown code in a file with a .py extension and run the following command in the terminal.
Output
immukul@192 linux-questions-code % python code.py 38 130
Using subprocess Module
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(columnSize)
Output
immukul@192 linux-questions-code % python code.py 38 130
Alternative Methods
You can also use the shutil module which provides a more cross-platform solution:
import shutil
columns, rows = shutil.get_terminal_size()
print(f"Columns: {columns}")
print(f"Rows: {rows}")
Another approach using the os.get_terminal_size() function (Python 3.3+):
import os
size = os.get_terminal_size()
print(f"Columns: {size.columns}")
print(f"Rows: {size.lines}")
Understanding the stty Command
It can be easily seen that in both approaches using os.popen() or subprocess.check_output(), we are making use of Linux's utility command stty, which is used to print the terminal line settings or the characteristics of the Linux terminal. From this output, we extract the height and width values.
| Method | Advantages | Disadvantages |
|---|---|---|
| os.popen() | Simple to use, works on older Python versions | Less secure, deprecated in favor of subprocess |
| subprocess.check_output() | More secure, recommended approach | Slightly more complex syntax |
| shutil.get_terminal_size() | Cross-platform, built-in Python function | Available only in Python 3.3+ |
| os.get_terminal_size() | Direct OS call, efficient | Available only in Python 3.3+ |
Conclusion
Both the os.popen() and subprocess approaches will work in latest and older versions of Python, but it is recommended to use the subprocess method as it is considered more secure and future-proof. For modern Python applications, shutil.get_terminal_size() or os.get_terminal_size() provide cleaner, cross-platform solutions.
