i need open writable file handle in python , hand off file descriptor function in .net assembly (accessed via pythonnet's clr module.
getting python file object win32 handle* straightforward, shown in this question:
import clr microsoft.win32.safehandles import safefilehandle system.io import filestream, fileaccess pyf=open("c:/temp/testing123.txt","w") fileno=pyf.fileno() print fileno # 6 handle = msvcrt.get_osfhandle(fileno) print handle # 1832l according msdn, should possible construct standard filestream object either straight intptr (the handle) or safefilehandle wrapper.
filestream(intptr, fileaccess) filestream(safefilehandle, fileaccess) the problem is... how can convince clr module cast handle intptr?
i've tried various versions of following, give me errors:
filestream(intptr(handle), true) filestream(intptr(int64(handle), true) filestream(intptr(int32(handle), true) safefilehandle(intptr(handle), true) ... => typeerror ("value cannot converted system.intptr") any suggestions how darn file handle c#?
probably bit late answer, this have worked?
from contextlib import contextmanager import ctypes import io import os, sys import tempfile libc = ctypes.cdll(none) c_stdout = ctypes.c_void_p.in_dll(libc, 'stdout') @contextmanager def stdout_redirector(stream): # original fd stdout points to. 1 on posix systems. original_stdout_fd = sys.stdout.fileno() def _redirect_stdout(to_fd): """redirect stdout given file descriptor.""" # flush c-level buffer stdout libc.fflush(c_stdout) # flush , close sys.stdout - closes file descriptor (fd) sys.stdout.close() # make original_stdout_fd point same file to_fd os.dup2(to_fd, original_stdout_fd) # create new sys.stdout points redirected fd sys.stdout = io.textiowrapper(os.fdopen(original_stdout_fd, 'wb')) # save copy of original stdout fd in saved_stdout_fd saved_stdout_fd = os.dup(original_stdout_fd) try: # create temporary file , redirect stdout tfile = tempfile.temporaryfile(mode='w+b') _redirect_stdout(tfile.fileno()) # yield caller, redirect stdout saved fd yield _redirect_stdout(saved_stdout_fd) # copy contents of temporary file given stream tfile.flush() tfile.seek(0, io.seek_set) stream.write(tfile.read()) finally: tfile.close() os.close(saved_stdout_fd)
Comments
Post a Comment