Week 5: Scripting

Video Notes

  • os.system will execute a command in a subshell, behaving as if you have run a command. 
    • Changes will not persist
    • os.system(“ls ..”)
  • in order to create a script, create a new file with a python extension:
    • vi test.py
    • type line, “#!/usr/bin/env python”
  • ls -l
    • l flag stands for “long”
    • tells us what we need to know about permissions
  • r = read, w = write, x = execute
    • first three refers to owner
    • 4-6 refer to group that owns file
    • last three refer to other people
  • chmod (change mode) is useful for changing permissions
    • rwx = 7
    • wx = 3
    • rw = 6
  • chmod u-X
    • remove execute permission from user

 

Lab

Before getting started, you should download the following two files and open them in a text editor (so you get syntax highlighting): http://stanford.edu/~jainr/basics.py has some python basics and http://stanford.edu/~jainr/tester.py has some code examples.  You should also check out Python's Popen and os modules -- os.system works for a lot of stuff, but it's a pretty blunt tool, and you can do a lot more with Popen and the os commands.

0. Pre-Lab Questions

What is the difference between subprocess.Popen and os.system? Hint: If you're doing multiple things that are computationally heavy, you should use subprocess

How would you access command-line arguments from a python script? Hint: Try googling: sys.argv[n]. What is sys.argv[0]?

1.  Write a Basic Script

Download the following file: 

shakespeare_sonnets.txt 

(To download shakespeare_sonnets.txt try right-clicking it and selecting “Save Link As...”)

Write a script that finds how many times the word "love" appears in the file. We'll count it even if it's a part of a word, say "lovely", and also if it's capitalized as in "Love". Verify with us!

If your script isn't already set up this way, make it so that your script can find the number of occurrences of ANY word. HINT: This involves pulling from the argumtents to the script.

How many times does the word "thee" appear?

How about the word "to"?

How about the word "eternal"?

Tips:

2. Write a scripting script

Now write a script that you can run ONCE, which determines the number of occurrences of the words "love", "thee", "to", and "eternal" from shakespeare_sonnets.txt all at once. This is a script that will run a script. It's almost like "meta" scripting. You should only need to run this script once!

Tips:

  • Recall os.system from lecture
  • Remember to import os