'Is there a way to get win32 file handle from pipe's C file descriptor (python)?
Searched for about 1 hour and still unable to find any relevant search results.
I want to wait on multiple pipes in a single thread, but unable to convert the fileno to its win32 handle.
The following code errors:
import multiprocessing as _mp
import win32event
import msvcrt
if __name__ == '__main__':
pipeout, pipein = _mp.Pipe()
win32event.WaitForSingleObject(msvcrt.get_osfhandle(pipeout.fileno()), win32event.INFINITE)
error:
Traceback (most recent call last):
File "D:/users/das/Mega/Project/Dev/umodbus2/lib2/selector/stackoverflow.py", line 8, in <module>
win32event.WaitForSingleObject(msvcrt.get_osfhandle(pipeout.fileno()), win32event.INFINITE)
OSError: [Errno 9] Bad file descriptor
Apparently the way C is implemented on windows means that fds have irrelevant values to their os handles, but how you convert between the 2 types of values is poorly documented, if at all for anything other than file objects.
It would be pretty dumb if windows was designed to not allow any way to do this, so how do I do it?
Solution 1:[1]
Solved my own question by reading the python standard lib source code
import multiprocessing as _mp
import _winapi
from functools import wraps
from threading import Thread
def thread(_f, _daemon=False):
"""decorate a function to run in its own thread"""
@wraps(_f)
def f(*args, **kwargs):
r = Thread(daemon=_daemon, target=_f, args=args, kwargs=kwargs)
r.start()
return r
return f
@thread
def sender(pipe, msg, time: (int, float) = 2.0):
from time import sleep
sleep(time)
pipe.send_bytes(msg)
if __name__ == '__main__':
pipeout, pipein = _mp.Pipe(False)
sender(pipein, b"hello world", 2)
bsize = 128
ov, err = _winapi.ReadFile(pipeout.fileno(), bsize, overlapped=True)
print("waiting")
waitres = _winapi.WaitForMultipleObjects([ov.event], False, _winapi.INFINITE)
print("done waiting")
nread, err = ov.GetOverlappedResult(True)
r = ov.getbuffer()
print("r:", r)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tex |
