Lecture 48:

posted May 2, 2013, 6:26 AM by Samuel Konstantinovich   [ updated May 2, 2013, 8:28 AM ]
Quiz today!!!!

After quiz:
1. Madlibs can be done with dictionaries...

2. Arguments to a command line program.

2a. Use the terminal, or SSH (putty)
Make a py file 'arguments.py' which contains these three lines of code:
import sys
print 'look:'
print sys.argv

Save the file and try running it on the terminal like:
python arguments.py
python arguments.py 1 2 3
python arguments.py hello my name_is

2b. In a web page, you can do a similar thing. Make a py file that makes a webpage:
#!/usr/bin/python
print 'Content-Type: text/html'
print
import sys
print sys.argv

Place this on the web server, and go to the URL as you would normally:
address/~username/file.py
then try adding a question mark followed by more text
address/~username/file.py?test
address/~username/file.py?test1,test2
address/~username/file.py?1 2 3 4


2c. You can isolate the part after the question mark as follows:
arguments=''
if len(sys.argv)>1:
    arguments=sys.argv[1]  
print sys.argv[0] #this always exists
print arguments #this is sometimes empty.


Remember, this is a tool you can use, here is an example:
#!/usr/bin/python
print 'Content-Type: text/html'
print
page = '''
<!DOCTYPE HTML>
<html>
<head>
  <title> REPLACE_TITLE </title>
</head>
<body>
REPLACE_BODY
</body>
</html>'''

body='''
Boring!<br>
try using a better url!!!!<br>
<a href="advancedDemo.py?OMG!">Try this link</a><br>
<a href="advancedDemo.py?1,2,3">or try this link</a><br>
<a href="advancedDemo.py?test,my,functions">OR this link</a><br>
<a href="advancedDemo.py?,,,,">Wuzz at this link?</a><br>'''
title='Superfly!'
  
import sys

command=sys.argv[0]
if len(sys.argv)>1:
    parameters=sys.argv
    title='Whoa!'
    body=str(parameters)   #you can change the body based on the parameters here, it is up to you what you want to do
#you could make the parameters be the files you open, or the size of the data you produce. It is totally up to you.


page=page.replace('REPLACE_TITLE',title)
page=page.replace('REPLACE_BODY',body)

print page



Comments