c - 使用从 C 扩展返回的文件描述符来读取 python 中的文件

标签 c windows python-2.7 cross-platform

当我尝试在 python 中读取文件时,它会阻止其他进程编辑该文件。即使文件以读取模式打开。

我找不到可以让我实现这一目标的选项。所以,我想做的是,将文件名发送到 C 扩展名,并使用所需的选项打开文件,然后从那里返回文件描述符。 并且,使用这个描述符获取文件对象并读取文件。

我试过的代码是:

C代码文件read.h

#include <python.h>

static PyObject* fileread(PyObject *self, PyObject *args)
{
    char* filename = NULL;
    int fd = 0;
    if (!PyArg_ParseTuple(args, "s", &filename)) {
        return NULL;
    }

    fd = _sopen(filename, 0x0000, 0x40, 0x0100);
    // _sopen(filename,_O_RDONLY, _SH_DENYNO, _S_IREAD);
    return Py_BuildValue("i", fd);
}

static PyMethodDef fileread_funcs[] = {
    { "fileread", (PyCFunction)fileread,
    METH_VARARGS, "read file in blocks" },
    { NULL, NULL, 0, NULL }
};

void initfileread(void)
{
    Py_InitModule3("fileread", fileread_funcs,
        "Extension for file read!");
}

并且,fileread.py 是:

import os
import fileread

def ReadDataBlockByBlock(dirPath, fileName):
    path = os.path.join(dirPath, fileName)

    if os.access(path, os.R_OK):
        fd = PyObjectAsFileDescriptor(fileread.fileread(path))
        fp = os.fdopen(fd,'r') #Is Error: Expects integer

    for block in read_in_chunks(fp):
        print block
        print '*' * 80

    os.close(fd)

 def read_in_chunks(file_object, chunk_size=1096):
    """Function (generator) to read a file piece by piece.
    Default chunk size: 1k."""

    while True:
        data = os.read(file_object, chunk_size)
        if not data:
            break
        yield data

当我在这里尝试执行 fdopen() 时,它会抛出一个错误。我做错了什么?

最佳答案

默认情况下,Python 不锁定文件,但如果需要,请参阅 fcntl 模块。

但是如果 Python 进程打开了文件,其他锁定文件的进程可能无法获得锁定。 (这是严重依赖操作系统的行为。)

要证明不是 Python 阻止了另一个进程访问文件,请打开两个不同的终端程序或 cmd 窗口,在这两个程序中启动 Python,然后在每个程序中打开文件进行读取。这应该有效,并且会表明它是另一个进程提示它无法打开(并锁定)您的 Python 进程已打开的文件,而不是 Python 本身获取文件上的锁。

一般来说,处理这个问题的最好方法是打开文件,进行文件操作,然后立即再次关闭它。但是不幸的是,如果您的编辑器不允许其他进程打开文件,那么您将不得不处理这个问题。您应该检查您的编辑器配置设置,看看它是否有一个您可以关闭的独占访问权限,如果没有,您应该考虑使用不同的编辑器。

关于c - 使用从 C 扩展返回的文件描述符来读取 python 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078380/

相关文章:

python - 如何在树莓派上安装 python 3 和 setuptools?

c - GHC 运行时如何处理文件 I/O?

c# - 以编程方式不可见地连接 Windows VPN

c# - Windows 本地文件系统访问 API

c++ - 独占打开文件/锁定文件

windows - 是什么决定了进程外的 COM 服务器需要多长时间才能注意到客户端已死亡?

python - pandas 数据框 to_csv 适用于 sep ='\n' 但不适用于 sep ='\t'

python - 为什么我在下面的代码中没有得到任何输出?

c - Linux:使用管道在进程之间发送信息

c - 为什么使用2个指针指向atmega微 Controller 中的寄存器地址?