You can use asyncio
module to achieve that, with Python 3.5, a working example can be as follows:
import asyncio
required_lines = 3
sleep_seconds = 2
async def count_lines(loop):
num_lines = open('file_name.csv').read().count('\n')
while num_lines != required_lines:
await asyncio.sleep(sleep_seconds)
num_lines = open('file_name.csv').read().count('\n')
loop = asyncio.get_event_loop()
loop.run_until_complete(count_lines(loop))
loop.close()
With Python 3.4, use the following count_lines
function instead of the above one:
@asyncio.coroutine
def count_lines(loop):
num_lines = open('file_name.csv').read().count('\n')
while num_lines != required_lines:
yield from asyncio.sleep(sleep_seconds)
num_lines = open('file_name.csv').read().count('\n')
Edit: for Python 2.7 you can use trollius
library as shown below (trollius
still works but it is no longer maintained!):
import trollius
from trollius import From
required_lines = 3
sleep_seconds = 2
@trollius.coroutine
def count_lines():
num_lines = open('file_name.txt').read().count('\n')
while num_lines != required_lines:
yield From(trollius.sleep(sleep_seconds))
num_lines = open('file_name.txt').read().count('\n')
loop = trollius.get_event_loop()
loop.run_until_complete(count_lines())