0

I have a generator that should return lines from file, and I want to improve it later to return only specific lines:

def f():
    with open ('a', 'r') as f:
        while True:
            l = f.readline()
            if l:
                yield l
            else:
                break

Now, this generator shuold be called from a function that shows the file always, something like:

def g():
    my_generator = f()
    while True:
        print(my_generator.next() if SOME_CONDITION else 'waiting for new input')
        # if got to StopIteration -> wait until a new line appears in file

How can I do this? can I recreate my_generator after it died, when I get a new line (how would I know a line was added?)

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • 2
    Not an answer - but this looks like a suitable use of asyncio. It seems this in general is non-trivial and maybe OS specific - try searching on SO for tailing a file, e.g.: https://stackoverflow.com/questions/12523044/how-can-i-tail-a-log-file-in-python – AChampion Dec 18 '18 at 15:54

1 Answers1

0

you can try this:

def g():
    iterable = iter(f())
    for x in iterable:
        while True:
            if not SOME_CONDITION:
                print('waiting for new input')
            else:
                break
        break
    for x in iterable:
        print(x)
Oyono
  • 377
  • 1
  • 8