Question

Python Chet is trying to create a tail program for his windows machine so he can...

Python

Chet is trying to create a tail program for his windows machine so he can see the last N lines of a file or list of files. He wants the program to be usable by his friends and family so when an argument does not get passed to the program it should display a usage message. This is shown by the parser object by default but it's not doing it for him. The code works just not this one aspect of it. How can he fix it so that the parser object does it on it's own?

Only one thing needs to be changed in the code. No need to add any additional print statements or conditions. The output should look like

usage: tail [-h] [-n LINES] files [files ...]

tail: error: too few arguments

Code:

import argparse as arg
import linecache as cache
import os.path

parser = arg.ArgumentParser(prog="tail", description="""Print the last lines of 
a file to standard output.  With more than one file, 
precede each with a header giving the file name.""")

parser.add_argument('files', nargs='*', help='A list of files to be tailed.')
parser.add_argument('-n', '--lines', type=int, dest='lines', default=10, 
                    help='The number lines to display from the bottom.')

arguments = parser.parse_args()
lines_to_print = arguments.lines
files_to_open = arguments.files

for filepath in files_to_open:
    print("FILE: {}".format(filepath))
    if os.path.exists(filepath) and os.path.isfile(filepath):
        with open(filepath, 'r') as tailed_file:
            filesize = len(tailed_file.readlines())
        for i in range(lines_to_print):
            print(cache.getline(filepath, i).rstrip('\n'))
0 0
Add a comment Improve this question Transcribed image text
Answer #1

The solution to the above question is given below with screenshot of output.

=====================================================

I kept the logic simple and i have tested all outputs.

I Have added comments in program so that it can be easily

understood.

If there is anything else do let me know in comments.

=====================================================

============ CODE TO COPY ===============================

tail.py

import argparse as arg
import linecache as cache
import os.path
import sys

if len( sys.argv ) == 1 :
                print("usage: tail [-h] [-n LINES] files [files ...]")
                print("tail: error: too few arguments")
                sys.exit(1)

parser = arg.ArgumentParser(prog="tail", description="""Print the last lines of 
a file to standard output.  With more than one file, 
precede each with a header giving the file name.""")

parser.add_argument('files', nargs='*', help='A list of files to be tailed.')
parser.add_argument('-n', '--lines', type=int, dest='lines', default=10, 
                    help='The number lines to display from the bottom.')

arguments = parser.parse_args()
lines_to_print = arguments.lines
files_to_open = arguments.files

for filepath in files_to_open:
    print("FILE: {}".format(filepath))
    if os.path.exists(filepath) and os.path.isfile(filepath):
        with open(filepath, 'r') as tailed_file:
            filesize = len(tailed_file.readlines())
        for i in range(lines_to_print):
            print(cache.getline(filepath, i).rstrip('\n'))

saved main.py import argparse as arg 1 import linecache as cache 2 import os.path import sys 4 5 if len( sys.argv) print(usa

=====================================================

Output :

c:NUsersDe-1\Desktop>python tail.py usage tail [-h] [-n LINES) files [files ...] tail: error: too few argunents C:UserDe-1\De

Add a comment
Know the answer?
Add Answer to:
Python Chet is trying to create a tail program for his windows machine so he can...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a python program and pseudocode The Program Using Windows Notepad (or similar program), create a...

    Write a python program and pseudocode The Program Using Windows Notepad (or similar program), create a file called Numbers.txt in your the same folder as your Python program. This file should contain a list on floating point numbers, one on each line. The number should be greater than zero but less than one million. Your program should read the following and display: The number of numbers in the file (i.e. count them) (counter) The maximum number in the file (maximum)...

  • I need help in Python. This is a two step problem So I have the code...

    I need help in Python. This is a two step problem So I have the code down, but I am missing some requirements that I am stuck on. Also, I need help verifying the problem is correct.:) 7. Random Number File Writer Write a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 500. The application should let the user specify how many random numbers the file...

  • Could I get some help with this assignment In this assignment, you'll write a program which...

    Could I get some help with this assignment In this assignment, you'll write a program which reads a text file, and prints a histogram of its word sizes. So, for example, the historgram should show the number of words of length 1, of length 2, etc., up to the number of words of length n, where n is some constant defined in your program. To obtain text files that are suitably long, you could try Project Gutenberg, a site containing...

  • Lab Exercise #11 Assignment Overview You will work with a partner on this exercise during your la...

    help with cse problem Lab Exercise #11 Assignment Overview You will work with a partner on this exercise during your lab session. Two people should work at one computer. Occasionally switch the person who is typing. Talk to each other about what you are doing and why so that both of you understand each step Part A: Class Date . Download the files for this laboratory exercise, then run the Python shell and enter the following commands: >>>import date >>help(...

  • The purpose of this assignment is to develop solutions that perform File IO and objects. Problem specifications are shown below with my changes in blue. 1. File Previewer Write a program that asks...

    The purpose of this assignment is to develop solutions that perform File IO and objects. Problem specifications are shown below with my changes in blue. 1. File Previewer Write a program that asks the user for the name of a text file. The program should display the first 10 lines of the file on the screen. If the file has fewer than 10 lines, the entire file should be displayed along with a message indicating the entire file has been...

  • Question I This question carries 20% of the marks for this assignment. You are asked to...

    Question I This question carries 20% of the marks for this assignment. You are asked to develop a set of bash shell script: Write a script that asks for the user's salary per month. If it is less or equals to 800, print a message saying that you need to get another job to increase your income, what you earn is the Minim living cost. If the user's salary is higher than 800 and below 2000, print a message telling...

  • In Python!! 1. Correcting string errors It's easy to make errors when you're trying to type...

    In Python!! 1. Correcting string errors It's easy to make errors when you're trying to type strings quickly. Don't forget to use quotes! Without quotes, you'll get a name error. owner = DataCamp Use the same type of quotation mark. If you start with a single quote, and end with a double quote, you'll get a syntax error. fur_color = "blonde' Someone at the police station made an error when filling out the final lines of Bayes' Missing Puppy Report....

  • Most system administrators would like to know the utilization of their systems by their users. On...

    Most system administrators would like to know the utilization of their systems by their users. On a Linux system, each user's login records are normally stored in the binary file /var/log/wtmp. The login records in this binary file can not be viewed or edited directly using normal Linux text commands like 'less', 'cat', etc. The 'last' command is often used to display the login records stored in this file in a human readable form. Please check the man page of...

  • So I can not get this to work properly and he does not want us using...

    So I can not get this to work properly and he does not want us using an array list. Below is the directions along with the code I have(Im not sure the code is in the right format)   ITSE 2321 – OBJECT-ORIENTED PROGRAMMING JAVA Program 7 – Methods: A Deeper Look Write a program that will help an elementary school student learn multiplication. Use a SecureRandom object to produce two positive one-digit integers. The program should then prompt the student...

  • PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything...

    PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything a course uses in a grading scheme, # like a test or an assignment. It has a score, which is assessed by # an instructor, and a maximum value, set by the instructor, and a weight, # which defines how much the item counts towards a final grade. def __init__(self, weight, scored=None, out_of=None): """ Purpose: Initialize the GradeItem object. Preconditions: :param weight: the weight...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT