Much simpler than C.
I’ve already programmed cat command in C in another programming series – Linux Programming last year. This time, let’s make it with Python! It’s way simpler and cleaner than the other.
In one of my other programming series – Linux Programming, I’ve written about how we can actually program Linux commands with C. And this time, because we’ve been through Python’s basics for the past week, why don’t we merge what we’ve learned in both posts from STEM with Python and Linux Programming to build Linux commands with Pythion?
For a starter, here’s cat command written in Pythion by accessing the kernel’s APIs.
The code:
cat.py
import sys
# Check if the number of arguments is correct
if len(sys.argv) != 2:
print("Usage: cat.py <file>")
sys.exit(1)
# Open the file
try:
with open(sys.argv[1], 'r') as file:
# Read and print the contents of the file
print(file.read())
except FileNotFoundError:
print(f"Error: Unable to open file {sys.argv[1]}")
sys.exit(1)
I assume you can understand most of them without any detailed explanations, but one thing I may need to mention is the following part:
if len(sys.argv) != 2:
The reason it specifies ‘! = 2’ is because the first argv[0] receives the executed program’s name. So, argv is always more than 1, and when you handle the command line arguments in your program, you always have to start it from argc[1] as it opens the file in ‘open(sys.argv[1], ‘r’)’ in the program. I explained the detailed logic in another post: here.
A sample file to read
test.txt
AAA
BBB
CCC
DDD
EEE
The executed result:
$python3 cat.py test.txt
AAA
BBB
CCC
DDD
EEE
Afterthoughts:
So, what I did here is just re-programmed what I did in Linux Programming – Part 11: Program Cat Command. Since Python is gaining more attraction from developers nowadays, you wouldn’t waste your time learning the basics of the scripting language. Additionally, I temporarily stopped updating the Linux Programming series, but I want to restart it any time soon!