Другими словами,
- Мы хотим, чтобы выполнение программы продолжалось без ожидания возврата write_to_file(linesBuffer),< /li>
Но мы также хотим быть уверены, что каждый вызов write_to_file(linesBuffer) в конечном итоге возвращает результат.
Когда мы удалите await из строки write_to_file(linesBuffer), в результате ни одна из команд печати внутри функции write_to_file(linesBuffer) никогда не будет выполнена. Поэтому мы не можем просто изменить await write_to_file(linesBuffer) на write_to_file(linesBuffer).
Проблема в коде заключается в том, что множество последовательных вызовов await write_to_file (linesBuffer) приводит к очень медленной работе программы.
Вот код:
import os
import platform
import asyncio
numLines = 10
def get_source_file_path():
if platform.system() == 'Windows':
return 'C:\\path\\to\\sourceFile.txt'
else:
return '/path/to/sourceFile.txt'
async def write_to_file(linesBuffer):
print("inside Writing to file...")
with open('newFile.txt', 'a') as new_destination_file:
for line in linesBuffer:
new_destination_file.write(line)
#get the name of the directory in which newFile.txt is located. Then print the name of the directory.
directory_name = os.path.dirname(os.path.abspath('newFile.txt'))
print("directory_name: ", directory_name)
linesBuffer.clear()
#print every 1 second for 2 seconds.
for i in range(2):
print("HI HO, HI HO. IT'S OFF TO WORK WE GO...")
await asyncio.sleep(1)
print("inside done Writing to file...")
async def read_source_file():
source_file_path = get_source_file_path()
linesBuffer = []
counter = 0
print("Reading source file...")
print("source_file_path: ", source_file_path)
#Detect the size of the file located at source_file_path and store it in the variable file_size.
file_size = os.path.getsize(source_file_path)
print("file_size: ", file_size)
with open(source_file_path, 'r') as source_file:
source_file.seek(0, os.SEEK_END)
while True:
line = source_file.readline()
new_file_size = os.path.getsize(source_file_path)
if new_file_size < file_size:
print("The file has been truncated.")
source_file.seek(0, os.SEEK_SET)
file_size = new_file_size
linesBuffer.clear()
counter = 0
print("new_file_size: ", new_file_size)
if len(line) > 0:
new_line = str(counter) + " line: " + line
print(new_line)
linesBuffer.append(new_line)
print("len(linesBuffer): ", len(linesBuffer))
if len(linesBuffer) >= numLines:
print("Writing to file...")
await write_to_file(linesBuffer) #When we remove await from this line, the function never runs.
print("awaiting Writing to file...")
linesBuffer.clear()
counter += 1
print("counter: ", counter)
if not line:
await asyncio.sleep(0.1)
continue
#detect whether or not the present line is the last line in the file. If it is the last line in the file, then write the line to the file.
if source_file.tell() == file_size:
print("LAST LINE IN FILE FOUND. Writing to file...")
await write_to_file(linesBuffer)
print("awaiting Writing to file...")
linesBuffer.clear()
counter = 0
async def main():
await read_source_file()
if __name__ == '__main__':
asyncio.run(main())
Подробнее здесь: https://stackoverflow.com/questions/790 ... n-parallel
Мобильная версия