Python @ DjangoSpin

PyPro #16 Emulate tail command of Unix in Python

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Emulate tail command of Unix in Python: Python script to emulate tail command of Unix.

Emulate tail command of Unix in Python

# In Unix, the 'tail -n fileName' command displays the last n lines of the file 'fileName'.
# Write a program in Python to emulate the same functionality.
# Ask the user for the filename whose tail is to be displayed, and the number of lines comprising the tail.
# Output the last whatever-the-input lines.


fileName = input('Please enter the name of the file you wish view the tail of: ')
numberOfLines = int(input('Please enter the number of lines in the tail that you wish to view: '))

fileHandler = open( fileName, 'r' )

# list to store the tail
lines = []

# maintaining a n-line window using pop() method of lists. pop(0) removes the first element in the list i.e. least recent of the n lines
for line in fileHandler.readlines():
    lines.append(line)
    if len(lines) > numberOfLines:
        lines.pop(0)

fileHandler.close()

# Some text to replicate Unix command syntax.
print('\nExecuting command: tail -' + str(numberOfLines) + " " + fileName + "\n")

# displaying the tail
for line in lines:
    print(line, end="")



# If you are trying this on an online interpreter such as repl.it, you will have to create the file first using the open() function, and fill it with some sample lines, such as below.
# fileHandler2 = open('log_file.log', 'w')
# fileHandler2.write('Checking environment variables...\n')
# fileHandler2.write('Connecting to database...\n')
# fileHandler2.write('Connected to database.\n')
# fileHandler2.write('Performing some pseudo-work...\n')
# fileHandler2.write('Pseudo-work done.\n')
# fileHandler2.write('Script executed successfully.\n')
# fileHandler2.write('Check errors.log for errors.\n')
# fileHandler2.close()
Try it here.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply