



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Goals In lab 4 we will endeavor to learn some of the basics of using a high level scripting language in the Unix software development environment. You will build several scripts to perform small tasks using the Python scripting language. Thus the goals of this lab are:
Exercise 4.2: Building a Simple Filter There are many methods for building a simple filter in Python, to read lines from standard input and write results to standard output. We will use the fileinput python library to create and perform simple filtering tasks. Create and add a file called simplefilter.py to your lab04 working directory. For this step and for all future steps, you should make the script interpretable by the python interpreter and executable from the command line by performing the tasks of part 4.1 on your script file. Add the following lines to your simplefilter.py script: import fileinput for line in fileinput.input(): print "Got line: <%s>" % line The fileinput library is a set of routines for doing exactly this very common task of reading lines of text from standard input so that they can be processed and filtered. The import keyword is how you tell a python script that you want to use commands or functions from a given library (look at the library reference manual on the python web site: http://docs.python.org/lib/lib.html for documention on the fileinput and all other python libraries). You can run your simplefilter.py script interactively to see how it works: [harry@nisl lab04]$ simplefilter.py Hello world This is my second line yet another line Got line: Got line: Got line: [harry@nisl lab04]$ In the above example I typed in the first 3 lines (in italics). I then typed in a Ctrl-d. After entering Ctrl-d, the text will be sent to the python script, and you will get the results shown where the text of the 3 lines that were typed in are displayed to standard output. You may need to enter a Ctrl-d on a line by itself in order to exit from running the script interactively. Here is another way that you can use a pipe to test your simple filter. Create a file and type in some lines of text. Then use the cat command and a pipe to send the input into your filter: [harry@nisl lab04]$ vi junk ... I edited the file called junk here and typed in a few lines of text ... [harry@nisl lab04]$ cat junk First line another line This is my last line [harry@nisl lab04]$ cat junk | simplefilter.py Got line: Got line: Got line:
>>> s = "This is a String. This is only my String. Testing 1 2 3 4." >>> print s This is a String. This is only my String. Testing 1 2 3 4. >>> dir(s) ['add', 'class', 'contains', 'delattr', 'doc', 'eq', 'ge', 'getattribute', 'getitem', 'getnewargs', 'getslice', 'gt', 'hash', 'init', 'le', 'len', 'lt', 'mod', 'mul', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'rmod', 'rmul', 'setattr', 'str', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] The dir() command can be used in an interactive session to discover all of the functions and attributes that an object contains. Since a string variable is actually an object, there are methods that are available that can be used to manipulate the string. For example, continuing from the previous interactive session: >>> s.lower() 'this is a string. this is only my string. testing 1 2 3 4.' >>> s.upper() 'THIS IS A STRING. THIS IS ONLY MY STRING. TESTING 1 2 3 4.' >>> s.swapcase() 'tHIS IS A sTRING. tHIS IS ONLY MY sTRING. tESTING 1 2 3 4.' This is an example of invoking the lower() upper() and swapcase() methods on the string object s. Modify your simplefilter.py script from exercise 4.2. Note that the line variable is actually a string, like the string s object in the previous example. Modify your simplefilter.py script so that it does a case insensitive search for the magic word. For example, once modified you should be able to run an interactive session that looks like the following: [harry@nisl lab04]$ simplefilter.py This is a line Another line Hello hello hElLo Say the magic word Say the magic word Hi, nice to meet you Hi, nice to meet you Hi, nice to meet you Once you are satisfied with your work, commit your simplefilter.py script to the repository. Exercise 4.3: Functions and More Strings In this part of the lab we will look at defining functions in a Python script. As you saw in the previous section of the lab, there are many built in methods that can be called in order to manipulate string objects. Unfortunately, reversing a string is not one of them. We could add a method to the basic Python string object to perform this, by extending the Python language. But this would be beyond the scope of this lab. So instead we will define a simple python function that will take a single string as a parameter, and will return a new string that is the result of reversing the character order of the characters in the input string. Before we start, a few hints on how you might solve this task. Your function will need to access and manipulate the characters of a string. Strings in Python are sequences, just like lists, and characters may be accessed using list access syntax. For example, to access the individual characters of a string you could (the following was done from an interactive python session):
>>> orig = "Hi!" >>> for char in orig: ... print char ... H i ! Notice that in the for loop, each char is accessed one by one, and printed out to standard output. The same task can be accomplished by using an explicit index variable in a loop: >>> for i in range(0, len(orig)): ... print orig[i] ... H i ! This could especially useful to, for example, access the characters starting from the end and progressing to the beginning of the string: >>> i = len(orig)- >>> while (i >= 0): ... print orig[i] ... i -= 1 ... ! i H One other example/hint that might be useful in implementing your reverse() function. Recall that strings are overloaded in Python so that you can use the + operator to concatenate strings together. So for example, you could append or prepend a character to a string doing things like: >>> orig+'M' 'Hi!M' >>> 'M'+orig 'Mhi!' With those example in mind, you are to write a filter that will read lines from standard input, and write the reversed version of the line to standard output. Create an interpretable and executable python script file called reverse.py for this portion of the lab. You file should look something like this: #!/usr/bin/env python import fileinput
for line in fileinput.input(): print reverse(line) Of course you need to provide your implementation of the reverse() function at the location indicated. As stated above, your reverse() function takes a string as input. It should returned the reversed string as the result of calling the function. Also, to make your output more readable, you should strip the newline from your line before calling the reverse function, as you did in part 4.2. Once your reverse function is working properly, you should be able to run it with a file or interactively, and get a result similar to this:
Lab 04 Extra Credit: Reimplement the wc Command as a Python Script The following task can be undertaken for extra credit. The extra credit will be worth 15 extra points for undergraduate students, and 5 extra points for graduate students. The task is to reimplement the wc command as a python script. Call your script wc.py. You should be able to use the palindrome.py as a base for your work. You need to support the -l, -w and -c options. In fact, asking for help from your wc.py filter should produce the following usage message: [harry@nisl lab04]$ wc.py -h Usage: wc.py [options] options: -h, --help display this help and exit -c, --bytes print the byte counts -l, --lines print the newline counts -w, --words print the word counts You will need to, of course, correctly specify and parse the options using the optparse Python library, as well as implement the logic to display the counts. Your implementation should give exactly the same results when filtering standard input as the wc command: [harry@nisl lab04]$ cat hello.py | wc 3 6 51 [harry@nisl lab04]$ cat hello.py | wc -w 6 [harry@nisl lab04]$ cat hello.py | wc.py 3 6 51 [harry@nisl lab04]$ cat hello.py | wc.py -w 6 To get full credit you need to implement the logic and the indicated options, and add and commit your wc.py script to your lab04 repository directory.