title: How to convert python script to web interface
body: <p>I'm trying to convert this python script (diff.py)</p>
  
  <pre><code>http://www.aaronsw.com/2002/diff/
  </code></pre>
  
  <p>into the exact same thing at my site, ie, a web interface. He supplies the script which you can download and I get it to work on my windows computer via command line, but I want it to work on my server also. I am so close. Here is what I have so far.</p>
  
  <p>Here is my html document - </p>
  
  <pre><code>&lt;form action="/cgi-bin/diff.py" method="get"&gt;&lt;p&gt;
  &lt;strong&gt;Old URL:&lt;/strong&gt; &lt;input name="old" type="text"&gt;&lt;br&gt;
  &lt;strong&gt;New URL:&lt;/strong&gt; &lt;input name="new" type="text"&gt;&lt;br&gt;
  &lt;input value="Diff!" type="submit"&gt;
  &lt;/p&gt;&lt;/form&gt;
  </code></pre>
  
  <p>Here is my edited diff.py script that is nearly working - </p>
  
  <pre><code>#!G:\Program Files\Python25\python.exe
  """HTML Diff: http://www.aaronsw.com/2002/diff
  Rough code, badly documented. Send me comments and patches.
  
  __author__ = 'Aaron Swartz &lt;me@aaronsw.com&gt;'
  __copyright__ = '(C) 2003 Aaron Swartz. GNU GPL 2 or 3.'
  __version__ = '0.22' """
  
  import cgi
  import cgitb; cgitb.enable()
  form = cgi.FieldStorage()
  reshtml = """Content-Type: text/html\n
  &lt;html&gt;
  &lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;/head&gt;
  &lt;body&gt;
  """
  print reshtml
  a = form['old'].value
  b = form['new'].value
  
  import difflib, string
  
  def isTag(x): return x[0] == "&lt;" and x[-1] == "&gt;"
  
  def textDiff(a, b):
      """Takes in strings a and b and returns a human-readable HTML diff."""
  
      out = []
      a, b = html2list(a), html2list(b)
      s = difflib.SequenceMatcher(None, a, b)
      for e in s.get_opcodes():
          if e[0] == "replace":
              # @@ need to do something more complicated here
              # call textDiff but not for html, but for some html... ugh
              # gonna cop-out for now
              out.append('&lt;del class="diff modified"&gt;'+''.join(a[e[1]:e[2]]) +   '&lt;/del&gt;&lt;ins class="diff modified"&gt;'+''.join(b[e[3]:e[4]])+"&lt;/ins&gt;")
          elif e[0] == "delete":
              out.append('&lt;del class="diff"&gt;'+ ''.join(a[e[1]:e[2]]) + "&lt;/del&gt;")
          elif e[0] == "insert":
              out.append('&lt;ins class="diff"&gt;'+''.join(b[e[3]:e[4]]) + "&lt;/ins&gt;")
          elif e[0] == "equal":
              out.append(''.join(b[e[3]:e[4]]))
          else: 
              raise "Um, something's broken. I didn't expect a '" + `e[0]` + "'."
      return ''.join(out)
  
  def html2list(x, b=0):
      mode = 'char'
      cur = ''
      out = []
      for c in x:
          if mode == 'tag':
              if c == '&gt;': 
                  if b: cur += ']'
                  else: cur += c
                  out.append(cur); cur = ''; mode = 'char'
              else: cur += c
          elif mode == 'char':
              if c == '&lt;': 
                  out.append(cur)
                  if b: cur = '['
                  else: cur = c
                  mode = 'tag'
              elif c in string.whitespace: out.append(cur+c); cur = ''
              else: cur += c
      out.append(cur)
      return filter(lambda x: x is not '', out)
  
  if __name__ == '__main__':
      import sys
      try:
          a, b = sys.argv[1:3]
      except ValueError:
          print "htmldiff: highlight the differences between two html files"
          print "usage: " + sys.argv[0] + " a b"
          sys.exit(1)
      print textDiff(open(a).read(), open(b).read())
  
  print '&lt;/body&gt;'
  print '&lt;/html&gt;'
  </code></pre>
  
  <p>This is the result I get in my browser - </p>
  
  <pre><code>htmldiff: highlight the differences between two html files usage: E:/xampp/cgi-bin/diff.py a b 
  </code></pre>
  
  <p>Can anyone see what's wrong?</p>
  
  <p>Ok, here is the error when I use print open(a).read() ---</p>
  
  <pre><code>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
   E:\xampp\cgi-bin\diff2.py in ()
     19 b = form['new'].value
     20 
     21 print open(a).read()
     22 
     23 
  builtin open = &lt;built-in function open&gt;, a = 'http://www.google.com', ).read undefined
  
  &lt;type 'exceptions.IOError'&gt;: [Errno 2] No such file or directory: 'http://www.google.com'
      args = (2, 'No such file or directory')
      errno = 2
      filename = 'http://www.google.com'
      message = ''
      strerror = 'No such file or directory'
  </code></pre>
  
  <p>Ok, I think I actually figured this out on my own. Here are the changes necessary. I stopped at the start of the original code - </p>
  
  <pre><code>#!G:\Program Files\Python25\python.exe
  """HTML Diff: http://www.aaronsw.com/2002/diff
  Rough code, badly documented. Send me comments and patches.
  
  __author__ = 'Aaron Swartz &lt;me@aaronsw.com&gt;'
  __copyright__ = '(C) 2003 Aaron Swartz. GNU GPL 2 or 3.'
  __version__ = '0.22' """
  
  
  import cgi
  import cgitb; cgitb.enable()
  form = cgi.FieldStorage()
  reshtml = """Content-Type: text/html\n
  &lt;html&gt;
  &lt;head&gt;&lt;title&gt;Tonys Test&lt;/title&gt;&lt;/head&gt;
  &lt;body&gt;
  """
  print reshtml
  old2 = form['old'].value
  new2 = form['new'].value
  
  import urllib2
  
  a = urllib2.urlopen(old2).read()
  b = urllib2.urlopen(new2).read()
  
  #print a
  #print b
  
  import difflib, string
  </code></pre>
  
  <p>Well, I spoke too soon. It works but without the highlighting of differences. I only get strikethrough for the old version. I tried adding in that part I cut out which supposedly does the highlighting but it doesn't work. I get my original error statement. I'll keep working at it.</p>
  
  <p>OK, finally working. I had to add this code at the end - </p>
  
  <pre><code>def htmlDiff(a, b):
      f1, f2 = a.find('&lt;/head&gt;'), a.find('&lt;/body&gt;')
      ca = a[f1+len('&lt;/head&gt;'):f2]
  
      f1, f2 = b.find('&lt;/head&gt;'), b.find('&lt;/body&gt;')
      cb = b[f1+len('&lt;/head&gt;'):f2]
  
      r = textDiff(ca, cb)
      hdr = '&lt;style type="text/css"&gt;&lt;!-- ins{background-color: #bbffbb} del{background-color: #ffcccc}--&gt;&lt;/style&gt;&lt;/head&gt;'
      return b[:f1] + hdr + r + b[f2:]
  
  
  print htmlDiff(a, b)
  print '&lt;/body&gt;'
  print '&lt;/html&gt;'
  </code></pre>
  
  <p>I found this code in the 0.1 version download. </p>