Fix Python 3 compatibility

This includes fixes related to the use of strings/bytes as well
dict.iteritems().

NOTE: Code like `iter(lambda: sys.stdin.read(65535), ''):` was causing some tests to deadlock when running with py3. Not all of the instances of this pattern are covered by tests, but I updated them anyway. Please let me know if you find any problems with them.