Question

In: Computer Science

For the second phase of your final project, you will provide the functionality to your command...

For the second phase of your final project, you will provide the functionality to your command interpreter. In this phase, you will add the functionality for command recognition and implement the HELP, QUIT, COPY, LIST, CD, SHOW and RUN functions.

Recall that some commands have no arguments, some have one and some have two and so your interface must handle a variable number of parameters.

Your command interpreter should do the following.

Display a prompt for the user.

  • Read the user's input.
  • Determine if the entered command is valid
  • If it is valid, execute it and then re-display the prompt.
  • If the command is not valid, display a specific, appropriate error message and re-display the prompt.  Be sure that your command interpreter differentiates between different errors that render a command invalid.
  • Continue until the user enters the command “QUIT”.

If the entered command is invalid or if the number of parameters to that command is incorrect your program will print the error message and then redisplay the prompt.

If the command is valid, your program will carry out the command.

Here are specifics for each of the commands.

HELP

List the valid commands and their proper syntax.  E.g.

You rang? > HELP

The valid commands are:

RUN executable-file

LIST

LIST directory

COPY old-filename new-filename

HELP

QUIT

SHOW file

            Simply prints the given file to standard output.

            

QUIT

Terminates the session.  E.g.

You rang? > QUIT

Goodbye.

COPY old-filename new-filename

Creates a copy of the source file.

When you implement the COPY command, you should verify that the source file exists and is readable.  If the destination file exists you should ask the user if they wish to overwrite it before opening it to write.  Once both files have been successfully opened simple read the characters on at a time from the source file and write them to the destination file.

CD directory

         Changes the working directory to the argument if it is a valid directory name.

Your shell should display a message indicating the new directory upon successful execution o the command.  You will need to use the chdir and getcwd commands as illustrated in the sample program chDir.cpp

LIST

Displays the files in a directory

Your LIST command takes either no arguments or one argument.  The contents of the directory specified by the argument should be listed or in the case of no argument, the contents of the current directory should be listed.  The syntax is:

            LIST

or

LIST directory

The algorithm for LIST is reasonable simple.

Open the directory

Read the first entry in the directory

While not all of the directory has been displayed

            Display the entry just read

            Read the next entry

Close the directory

Working with directories is a relatively low-level operation.  To access the contents of a directory we need to use a collection of system calls declared in the <dirent.h> header file.

opendir( dname )     is passed a c-string dname and returns a pointer to the directory dname  (type DIR*) if it is found and NULL otherwise.

readdir( dPointer )  is passed a DIR* and returns a pointer to the next entry in the directory linked to dPointer or NULL if there are no more entries.

closedir( dPointer )  closes the link to the directory

The directory entries are of type dirent, a structure that contains the member d_name, which contains the name of the current entry.

Refer to chapter 17 of your UNIX text for more on programming with directories.

RUN executable-file

Executes the given program.

Your RUN command takes one argument.  The executable file specified by the argument should be run and when finished, the prompt displayed.  The syntax is:

RUN executable-file

The algorithm for RUN would be as follows.

Fork a child process.

Execute the program in the child process.

Have the parent wait until the child is finished before continuing.

This will require the following library functions

fork( )                               creates a child process and returns the PID of the child process to the parent. The child gets 0.

execl( list of cstrings )      executes a program in the current process — the first argument is the path to the executable file, the remaining arguments are the strings of the command line

wait( )                               causes the parent to block until the child finishes

Refer to chapter 18 of your UNIX text for more extensive discussion of these concepts.

As always, your program should:

  • Contain carefully worded pre and post conditions for all functions.

Be readable with appropriate documentation and formatting

Solutions

Expert Solution

import os
from os import listdir
from os.path import isfile, join

while True:
    print("You rang?> ",end="")
    a = input()
    if a == "QUIT" :
        print ("Goodbye")
        exit(0)
    elif a == "HELP" :
        print("The valid commands are:\nSHOW file\nCD directory\nRUN executable-file\nLIST\nLIST directory\nCOPY old-filename new-filename\nHELP\nQUIT")
    elif "SHOW" in a:
        if ".txt" in a:
            a = a.split()[1]
        else:
            a = a.split()[1]+".txt"
        try:
            with open(a) as f:
                print(f.read())
        except Exception as e:
            print ("Error : " + str(e))
    elif "CD" in a:
        try:
            os.chdir(a.split()[1])
        except Exception as e:
            print("Error : "+str(e))
        finally:
            print("Current directory : "+os.getcwd())
    elif "RUN" in a:
        fname = a.split()[1]
        try:
            arg = dict(a.split()[2:])
        except:
            arg = {}
        #for windows : exec(open("./"+fname).read(),arg)
        try:
            n = os.fork()
        except Exception as e:
            print("Error in fork :"+str(e))
        else:
            if n==0:
                try:
                    exec(open("./"+fname).read(),arg)
                except Exception as e:
                    print("Error in file execution : "+str(e))
            else:
                os.wait()
    elif a == "LIST":
        files = [f for f in listdir(os.getcwd()) if isfile(join(os.getcwd(), f))]
        for i in files:
            print(i)
    elif "LIST" in a:
        dr = list(a.split()[1:])
        dr = ' '.join(dr)
        print(dr)
        files = [f for f in listdir(dr) if isfile(join(dr, f))]
        for i in files:
            print(i)
    elif "COPY" in a:
        src,dest = a.split()[1:]
        try:
            with open(src,"r") as f:
                a = f.read()
        except Exception as e:
            print("Error with source file : "+str(e))
        else:
            if os.path.exists(dest):
                print("Destination file aready exists. Press Y to overwrite, N to cancel")
                if(input()=="N"):
                    continue
            try:
                with open(dest,"w") as f:
                    f.write(a)
            except Exception as e:
                print("Error with destination file : "+str(e))
            else:
                print("File copied")
    
    else : print("Not a viable command. Enter HELP for list of commands")

Related Solutions

In the second milestone of your final project, you will complete your pre-opening strategy. You must...
In the second milestone of your final project, you will complete your pre-opening strategy. You must analyze the cost behaviors and systems of your industry and then conduct the relevant financial calculations to determine appropriate costing solutions. Be sure to use your work from Milestone One to inform your analysis and proposals. Scenario: Prior to Opening, Part II: Your market research indicated the following price ranges as optimal for your area: Dog Day Care o With pricing at $18 per...
In your final project you will be presenting your understanding of certain components of a Management...
In your final project you will be presenting your understanding of certain components of a Management Information System for an existing business. In order to complete this process, you will need to choose a company/industry and research the specific Management Information System of that company. Select a company of that you are familiar with or you feel is relevant in today’s business world. Discuss why you have selected that company and provide a brief synopsis of what the company does...
You are in a class titled Introduction to Artistic Expression, and your final project must be...
You are in a class titled Introduction to Artistic Expression, and your final project must be completed in class. You know that you will be given three objects and two boards to work with to create two separate displays. You also know that you must arrange the objects on the boards so they balance on a tiny pedestal. Once completed, one display will be a single object resting on a board balanced on top of a pedestal; the other will...
Instructions: You are to select a topic on continuous quality improvement for your final project. The...
Instructions: You are to select a topic on continuous quality improvement for your final project. The improvement must be in the health care sector and involve multiple disciplines, such as health information technology, laboratory, radiology, infection control, etc. You may select a real process or a hypothetical one. Your project selection is due by the end of this unit. Your project selection should include the following: · State the title of your quality improvement project. · Describe your topic by...
Your final project will satisfy the following scenario: You are writing a program that will act...
Your final project will satisfy the following scenario: You are writing a program that will act as an ATM machine by the end of this course. In order to access the ATM, the customer must enter their user name and their passcode. After 3 incorrect attempts at entering the user name and password, the program will end. The list of legitimate users along with their user ID, passcode, and account balance will be provided to you. There are only 5...
As part of your final project for this course, you researched different types of processors and...
As part of your final project for this course, you researched different types of processors and instruction sets. In addition, you created your own computer architecture including processor architecture, memory structure and algorithms, and an instruction set. You wrote a final report explaining your computer architecture and programming language characteristics and parameters. The project is an opportunity for you to synthesize the concepts you are learning in this course. Up to this point in the course, you communicated within your...
For your final project, you are to create a two-page web application of your choice. ASP.NET...
For your final project, you are to create a two-page web application of your choice. ASP.NET : C# You must include the following items: At least 5 different standard server controls At least 2 validation controls At least 1 navigation control ~ one must navigate back and forth to each page One session state element Upon completion of your two-page web application, you will provide a two page report describing the functions of the web application as well as each...
Phase 1 – ERD In this phase of the project you will create an ERD based...
Phase 1 – ERD In this phase of the project you will create an ERD based upon the following requirements and business rules. Limit your ERD to entities and relationships based on the business rules showed here. In other words, do not add realismto your design by expanding or refining the business rules.  However, make sure you include all attributes needed that would permit the model to be successfully implemented, including all primary and foreign keys. 1.Trinity College (TC) is divided...
Final Project: Leadership and Strategy Plan For this Final Project, you select a pressing health problem...
Final Project: Leadership and Strategy Plan For this Final Project, you select a pressing health problem affecting a community and develop a leadership and strategy plan for addressing the problem. You link this problem to a corresponding Healthy People 2020 objective(s).   Scenario   You are a new Health Program Planner recently hired by the Lake Troubled Shallows Department in Minnesota. Prior to your arrival, a comprehensive community health needs assessment was conducted by the Health Department. Based on the assessment, the...
You are working on your second project as an equity research intern at a bulge investment...
You are working on your second project as an equity research intern at a bulge investment bank. Your focus is in retail space, especially in the health and fitness sector. Currently, you are gathering information on a fast-growing chain fitness company called LuluYoga. You are interested in calculating the free cash flow of the firm. LuluYoga offers yoga classes in several major cities in the United States. Two major revenue resources are selling workout gear and membership passes for class...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT