首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python在windows上非阻塞读取文件

python在windows上非阻塞读取文件
EN

Stack Overflow用户
提问于 2016-03-23 03:42:33
回答 2查看 3.2K关注 0票数 9

我有一个在windows (Win7)上的程序员,它每隔x秒写入一个txt文件。现在我有了一个python脚本,它每隔x秒读取一次这个txt文件。当python脚本读取文件,同时另一个程序想要写入该文件时-写入程序崩溃(并显示权限错误)。因为我不能修改程序写入txt文件的方式,所以我必须尝试打开txt文件而不阻止写入程序。有没有人知道在这种情况下我可以做什么(阅读而不阻塞),我会非常高兴每一个关于这个话题的技巧!

尝试读取文件的程序代码如下所示:

代码语言:javascript
运行
复制
    with codecs.open(datapath, "r", 'utf-16') as raw_data:

         raw_data_x = raw_data.readlines()

我必须打开与“编解码器”的文件,因为它在unicode。

EN

回答 2

Stack Overflow用户

发布于 2016-03-24 07:07:11

在很长一段时间之后,我设法创建了一个在ctype中为您完成此任务的函数。请记住,只有当进程没有获得“独占”访问权限时,这才会起作用。如果是这样的话,你就不走运了,需要使用像shown here或implemented here这样的卷影复制服务。

不管怎样,这就是你的想法:

代码语言:javascript
运行
复制
import ctypes
from ctypes import wintypes
import os
import msvcrt

GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000

OPEN_EXISTING = 3
OPEN_ALWAYS = 4

ACCESS_MODES = {
    "r": GENERIC_READ,
    "w": GENERIC_WRITE,
    "r+": (GENERIC_READ|GENERIC_WRITE)
}

OPEN_MODES = {
    "r": OPEN_EXISTING,
    "w": OPEN_ALWAYS,
    "r+": OPEN_ALWAYS,
}


def open_file_nonblocking(filename, access):
    # Removes the b for binary access.
    internal_access = access.replace("b", "")
    access_mode = ACCESS_MODES[internal_access]
    open_mode = OPEN_MODES[internal_access]
    handle = wintypes.HANDLE(ctypes.windll.kernel32.CreateFileW(
        wintypes.LPWSTR(filename),
        wintypes.DWORD(access_mode),
        wintypes.DWORD(2|1),  # File share read and write
        ctypes.c_void_p(0),
        wintypes.DWORD(open_mode),
        wintypes.DWORD(0),
        wintypes.HANDLE(0)
    ))

    try:
        fd = msvcrt.open_osfhandle(handle.value, 0)
    except OverflowError as exc:
        # Python 3.X
        raise OSError("Failed to open file.") from None
        # Python 2
        # raise OSError("Failed to open file.")

    return os.fdopen(fd, access)

该函数在共享读写句柄的同时打开文件,允许多次访问。然后,它将句柄转换为普通的python文件对象。

完成后请确保关闭该文件。

票数 7
EN

Stack Overflow用户

发布于 2017-06-27 02:46:50

最近我不得不在跨平台兼容的python中的stdin和stdout上进行I/O读取。

用于linux的

对于linux,我们可以使用select模块。它是posix select函数的包装器实现。它允许你传递多个文件描述符,等待它们准备好。一旦他们准备好了,就会通知你,然后就可以执行read/write操作了。下面是一些小代码,可以帮助您了解情况

其中nodejs是一个带有nodejs镜像的docker环境

代码语言:javascript
运行
复制
  stdin_buf = BytesIO(json.dumps(fn) + "\n")
  stdout_buf = BytesIO()
  stderr_buf = BytesIO()

  rselect = [nodejs.stdout, nodejs.stderr]  # type: List[BytesIO]
  wselect = [nodejs.stdin]  # type: List[BytesIO]
  while (len(wselect) + len(rselect)) > 0:
            rready, wready, _ = select.select(rselect, wselect, [])
            try:
                if nodejs.stdin in wready:
                    b = stdin_buf.read(select.PIPE_BUF)
                    if b:
                        os.write(nodejs.stdin.fileno(), b)
                    else:
                        wselect = []
                for pipes in ((nodejs.stdout, stdout_buf), (nodejs.stderr, stderr_buf)):
                    if pipes[0] in rready:
                        b = os.read(pipes[0].fileno(), select.PIPE_BUF)
                        if b:
                            pipes[1].write(b)
                        else:
                            rselect.remove(pipes[0])
                if stdout_buf.getvalue().endswith("\n"):
                    rselect = []
            except OSError as e:
                break  

用于windows此代码示例包含涉及标准输入和标准输出的读写操作。现在,这段代码将不能在windows OS上运行,因为在windows上,select实现不允许将stdin、stdout作为参数传递。

Docs说:

Window上的

文件对象是不可接受的,但是套接字是可以接受的。在Windows上,底层的select()函数是由WinSock库提供的,并且不处理不是来自WinSock的文件描述符。

首先我必须提到,在windows上有很多非阻塞I/O读的库,比如asyncio(Python3),gevent(Python2.7),msvcrt,还有pywin32win32event,它会在你的套接字准备好read/write数据时提醒你。

An operation is performend on something that is not a socket

Handles only expect integer values等。

还有一些像twister这样的库,我还没有尝试过。

现在,为了在windows平台上实现上述代码中的功能,我使用了threads。下面是我的代码:

代码语言:javascript
运行
复制
    stdin_buf = BytesIO(json.dumps(fn) + "\n")
    stdout_buf = BytesIO()
    stderr_buf = BytesIO()

    rselect = [nodejs.stdout, nodejs.stderr]  # type: List[BytesIO]
    wselect = [nodejs.stdin]  # type: List[BytesIO]
    READ_BYTES_SIZE = 512

    # creating queue for reading from a thread to queue
    input_queue = Queue.Queue()
    output_queue = Queue.Queue()
    error_queue = Queue.Queue()

    # To tell threads that output has ended and threads can safely exit
    no_more_output = threading.Lock()
    no_more_output.acquire()
    no_more_error = threading.Lock()
    no_more_error.acquire()

    # put constructed command to input queue which then will be passed to nodejs's stdin
    def put_input(input_queue):
        while True:
            sys.stdout.flush()
            b = stdin_buf.read(READ_BYTES_SIZE)
            if b:
                input_queue.put(b)
            else:
                break

    # get the output from nodejs's stdout and continue till otuput ends
    def get_output(output_queue):
        while not no_more_output.acquire(False):
            b=os.read(nodejs.stdout.fileno(), READ_BYTES_SIZE)
            if b:
                output_queue.put(b)

    # get the output from nodejs's stderr and continue till error output ends
    def get_error(error_queue):
        while not no_more_error.acquire(False):
            b = os.read(nodejs.stderr.fileno(), READ_BYTES_SIZE)
            if b:
                error_queue.put(b)

    # Threads managing nodejs.stdin, nodejs.stdout and nodejs.stderr respectively
    input_thread = threading.Thread(target=put_input, args=(input_queue,))
    input_thread.start()
    output_thread = threading.Thread(target=get_output, args=(output_queue,))
    output_thread.start()
    error_thread = threading.Thread(target=get_error, args=(error_queue,))
    error_thread.start()

    # mark if output/error is ready
    output_ready=False
    error_ready=False

    while (len(wselect) + len(rselect)) > 0:
        try:
            if nodejs.stdin in wselect:
                if not input_queue.empty():
                    os.write(nodejs.stdin.fileno(), input_queue.get())
                elif not input_thread.is_alive():
                    wselect = []
            if nodejs.stdout in rselect:
                if not output_queue.empty():
                    output_ready = True
                    stdout_buf.write(output_queue.get())
                elif output_ready:
                    rselect = []
                    no_more_output.release()
                    no_more_error.release()
                    output_thread.join()

            if nodejs.stderr in rselect:
                if not error_queue.empty():
                    error_ready = True
                    stderr_buf.write(error_queue.get())
                elif error_ready:
                    rselect = []
                    no_more_output.release()
                    no_more_error.release()
                    output_thread.join()
                    error_thread.join()
            if stdout_buf.getvalue().endswith("\n"):
                rselect = []
                no_more_output.release()
                no_more_error.release()
                output_thread.join()
        except OSError as e:
            break

所以对我来说最好的选择就是线程。如果你想了解更多,这篇文章是nice read

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36163715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档