I am finding that if the loop is terminated before the "with open('filename') as f" loop completes, the file is never closed.
The code below shows the essential problem. On the Unix port, running on linux, all three files (sync_test.txt, async_test.txt, term_file.txt) are successfully closed and written. On the pyboard port, the file async_test.txt is not written. I’m guessing that this has something do do with the buffer that the file is being written to , or garbage collection, but don’t really understand how they work. Would manually calling the garbage collector at the end of the terminator ensure the "async_test.txt" file gets written?
What is a better way to write to a file from a coroutine that ensures that the file is written if the loop is terminated by an independent coroutine?
Code: Select all
import uasyncio as asyncio
def sync_file_write(name):
with open(name,'w') as f:
for i in range(5):
f.write('sync_'+str(i)+'_')
async def file_write(name):
with open(name,'w') as f:
for i in range(50):
f.write('async_'+str(i)+'_')
await asyncio.sleep(1)
async def terminator(name, n):
with open(name,'w') as f:
for i in range(n):
f.write('term_'+str(i)+'_')
await asyncio.sleep(1)
print('start')
sync_file_write('sync_test.txt')
loop=asyncio.get_event_loop()
loop.create_task(file_write('async_test.txt'))
loop.run_until_complete(terminator('term_file.txt',10))
print('stop')