在Python中,如何传递ctypes文件描述符来打开文件?

时间:2016-12-06 23:50:13

标签: python windows file-io

我正在尝试重现类似On Windows, how to open for writing a file already opened for writing by another process?中的内容 所以我按照Piotr Dobrogost的回答,修改了Using a struct as a function argument with the python ctypes module的代码,将标志和属性更改为我的目的(取自https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspxhttp://unix.superglobalmegacorp.com/Net2/newsrc/sys/fcntl.h.html)并添加Python(使用3.3版本)open功能:     来自os导入路径     来自ctypes进口*     来自ctypes.wintypes import *

GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000

FILE_SHARE_DELETE = 0x00000004
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
FILE_SHARE_READ_WRITE = (FILE_SHARE_READ | FILE_SHARE_WRITE)

OPEN_EXISTING = 3

FILE_ATTRIBUTE_NORMAL = 128
FILE_ATTRIBUTE_TEMPORARY = 256

O_RDONLY =  0x0000      # open for reading only 
O_WRONLY = 0x0001       # open for writing only 
O_RDWR = 0x0002     # open for reading and writing 
O_ACCMODE = 0x0003      # mask for above modes 
O_APPEND = 0x0008       # set append mode 

INVALID_HANDLE_VALUE = -1
LPOVERLAPPED = c_void_p
LPSECURITY_ATTRIBUTES = c_void_p

NULL = 0
FALSE = BOOL(0)
TRUE = BOOL(1)

def CreateFile(filename, access, sharemode, creation, flags):
    return HANDLE(windll.kernel32.CreateFileW(
        LPWSTR(filename),
        DWORD(access),
        DWORD(sharemode),
        LPSECURITY_ATTRIBUTES(NULL),
        DWORD(creation),
        DWORD(flags),
        HANDLE(NULL)
    ))


def translate_path(fpath):
    fpath = path.abspath(fpath)
    if fpath[len(fpath)-1] == '\\' and fpath[len(fpath)-2] == ':':
        fpath = fpath[:len(fpath)-1]
    return '\\??\\%s' % fpath

link_name = 'G:\\MATLAB\\Chronos_Python\\test.txt'
link_name = path.abspath(link_name)

hFile = CreateFile(link_name, GENERIC_READ, FILE_SHARE_WRITE, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL)

if hFile == HANDLE(INVALID_HANDLE_VALUE):
   raise Exception('Failed to open directory for junction creation.')

cFile = ctypes.cdll.msvcrt._open_osfhandle(hFile,O_RDONLY)
pyFile = open(cFile,'r')
pyFile.read()
pyFile.close()
ctypes.cdll.msvcrt._close(cFile)

windll.kernel32.CloseHandle(hFile)

但在pyFile = open(cFile,'r')行我得

  

OSError:[Errno 9]错误的文件描述符

这可能是非常基本的东西,因为我是python的新手...... 如果有人能帮助我修复它,我将非常感激。

1 个答案:

答案 0 :(得分:0)

假设文件句柄已正确生成,我认为您的问题可能就在这里:

pyFile = open(cFile,'r')

您正在尝试打开C运行时文件描述符,因此您需要在python中使用fdopen函数:

pyFile = os.fdopen(cFile, 'r')

您可能希望在此处查看文档 - python通过Windows上的标准库公开一些msvcrt函数: https://docs.python.org/3.6/library/msvcrt.html#msvcrt.open_osfhandle