In the C programming language, I often have done the following:
while ((c = getch()) != EOF) {
 /* do something with c */
}
In Python, I have not found anything similar, since I am not allowed to set variables inside the evaluated expression. I usually end up with having to setup the evaluated expression twice!
c = sys.stdin.read(1)
while not (c == EOF):
 # Do something with c
 c = sys.stdin.read(1)
In my attempts to find a better way, I've found a way that only require to setup and the evaluated expression once, but this is getting uglier...
while True:
 c = sys.stdin.read(1)
 if (c == EOF): break
 # do stuff with c
So far I've settled with the following method for some of my cases, but this is far from optimal for the regular while loops...:
class ConditionalFileObjectReader:
 def __init__(self,fobj, filterfunc):
  self.filterfunc = filterfunc
  self.fobj = fobj
 def __iter__(self):
  return self
 def next(self):
  c = self.fobj.read(1)
  if self.filterfunc(c): raise StopIteration
  return c
for c in ConditionalFileObjectReader(sys.stdin,lambda c: c == EOF):
 print c
All my solutions to solve a simple basic programming problem has become too complex... Do anyone have a suggestion how to do this the proper way?
 
     
     
     
    