Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivialent of C programming techniques (while loops)

Tags:

python

c

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?

like image 886
Dog eat cat world Avatar asked Jun 21 '11 14:06

Dog eat cat world


1 Answers

You would usually use a for loop in Python:

for c in sys.stdin.read():
    # whatever

If you don't want to buffer the whole stdin in memory at once, you can also add some buffering with a smaller buffer yourself.

Note that the constant EOF does not exist in Python. read() will simply return an empty string if no data is left in the stream.

like image 75
Sven Marnach Avatar answered Sep 30 '22 19:09

Sven Marnach