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...

  • 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...

  • could you please help me with this problem, also I need a little text so I...

    could you please help me with this problem, also I need a little text so I can understand how you solved the problem? import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static...

  • 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...

  • Python Coding The script, `eparser.py`, should: 1. Open the file specified as the first argument to...

    Python Coding The script, `eparser.py`, should: 1. Open the file specified as the first argument to the script (see below) 2. Read the file one line at a time (i.e., for line in file--each line will be a separate email address) 3. Print (to the screen) a line that "interprets" the email address as described below 4. When finished, display the total number of email addresses and a count unique domain names Each email address will either be in the...

  • !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random...

    !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random text with my generateText method, you can move on to the second step. Create a third class called Generator within the cs1410 package. Make class. This class should have a main method that provides a user interface for random text generation. Your interface should work as follows: Main should bring up an input dialog with which the user can enter the desired analysis level...

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