使用Python的选择投票()演示多个文件的异步写入

2024-04-23 10:14:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个示例Python脚本,以了解如何使用选择投票(),并与同步版本进行性能比较。 我正在BSD系统上测试。在

但是,似乎我仍在同步执行,我看不出哪里出错了,也不知道如何调试脚本。在

这是我目前为止的代码

import os
import fcntl
import select
poll = select.poll()

big_text = open('big-text.txt', 'r').read()

files_data = {}

for i in range(FILES_NO):
    file_name = 'data/file_{}'.format(i)
    fd = open(file_name, 'w')
    fcntl.fcntl(fd, fcntl.F_SETFL | os.O_NONBLOCK)

    files_data[fd.fileno()] = {}
    files_data[fd.fileno()]['fd'] = fd
    files_data[fd.fileno()]['bytes_wrote'] = 0
    files_data[fd.fileno()]['filename'] = file_name

    poll.register(fd)

def write(files_data, fileno, text):
    files_data[fileno]['fd'].write(text)
    files_data[fileno]['bytes_wrote'] += len(text)

chunk_size = 8192

while True:
    polled = poll.poll(0)

    if not polled:
        break

    for fileno, flags in polled:
        if flags & select.POLLOUT:
            bytes_wrote = files_data[fileno]['bytes_wrote']
            file_name = files_data[fileno]['filename']

            next_chunk = big_text[bytes_wrote:bytes_wrote + chunk_size]
            write(files_data, fileno, next_chunk)

            if len(next_chunk) == 0:
                poll.unregister(fileno)

有什么想法吗?在


Tags: textnameimportdatabytesfilesselectfile