Linux and Python combined; using Linux “more” command in Python
Introduction
In this article, we’ll dive into a Python script that reads and displays the content of a python file with a scrolling effect. The script utilizes modules like os, time, sys, and pynput for terminal operations, timing, system arguments, and keyboard event handling respectively.
Body
Script Breakdown
- Imports and Initial Setup:
import os, time, sys
from pynput import keyboardThe code imports essential modules. The os module interacts with the operating system, time handles time-related tasks, sys deals with system-specific parameters and functions, and pynput monitors and controls input devices.
Install Python Packages
Before running the script, you’ll need to install the necessary Python packages. Run these commands in your terminal:
pip install pynput2. Terminal Size and Command-line Argument:
size = os.get_terminal_size()[1]
args = sys.argv[1:]
assert len(args) == 1, "invalid arguments"This segment retrieves the terminal size and ensures that exactly one command-line argument is passed (the file to be read).
Get Parsa Saber’s stories in your inbox
Join Medium for free to get updates from this writer.
3. File Reading:
if os.path.exists(args[0]):
with open(args[0]) as f1:
txt = f1.read().split("\n")This portion checks if the file exists and reads its content line by line.
4. Display Logic:
line = 0
t_lines = 0
count = 0
while line < len(txt):
if t_lines <= size:
print(txt[line])
time.sleep(0.0009)
line += 1
t_lines += 1
else:
if not count:
print(f'{line / len(txt) * 100: .2f}%')
count += 1
with keyboard.Events() as events:
event = events.get(1e6)
if isinstance(event, keyboard.Events.Press):
if event.key == keyboard.Key.space:
t_lines = 0
count = 0
else:
print("file does not exist")The script initializes line and count variables and then enters a loop to print each line of the text. If the terminal is filled (t_lines exceeds size), it pauses and waits for a spacebar keypress to continue. The percentage of the file read is displayed during pauses.
Usage
To use the script, run it from the command line with the filename as an argument:
python yourfile.py file_nameReplace yourfile.py with the actual file name of your code and file_name with the name of the file you want to read.
Thank you for reading this article. Feel free to check out my GitHub Gist document more.py if you have any complications:
You can also visit my LinkedIn profile:








