簡體   English   中英

使用從C擴展名返回的文件描述符讀取python中的文件

[英]Using the file descriptor returned from C extension to read the files in python

當我嘗試使用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本身獲取了對該文件的鎖定。

通常,解決此問題的最佳方法是打開文件,執行文件操作,然后立即再次關閉它。 但是,不幸的是,如果您的編輯器不允許其他進程打開文件,那么您將不得不解決這個問題。 您應該檢查編輯器配置設置,以查看它是否具有可以關閉的獨占訪問權限,如果沒有,則應考慮使用其他編輯器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM