What is the proper way of communicating with named pipes on Windows from Python? I've googled it, and can't find any packages that wrap this communication.
There are:
- some descriptions of how to do it with pywin32 (I could not find how to connect to an existing pipe with it, though).
- This package: https://pypi.python.org/pypi/PyWPipe/ (had no luck with it either)
- A piece of code here, that I haven't yet tested: http://jonathonreinhart.blogspot.ru/2012/12/named-pipes-between-c-and-python.html
I need just to connect to an existing named pipe and read/write to it. I previously had only tried communication with serial port (using pySerial), and I'm surprised how little info I could find on named pipes in comparison to it. There's usually tons of guides for any purpose for Python.
I'll appreciate any help.
I have success with something like the following fragment. This code is derived from CaptureSetup/Pipes — Python on Windows — The Wireshark Wiki. It requires
win32pipe
andwin32file
from thepywin32
package.I don't know if it's 100% correct in the way it closes the pipe.
You referred to The Perils and Triumphs of Being a Geek: Named Pipes between C# and Python—Jonathon Reinhart. I tried it, but it wasn't able to create the named pipe. I wonder if that code only works to open a named pipe that has already been created by another process.
In order to connect to an existing named pipe you can utilize the
CreateFile
API provided through thepywin32
package. Since it took me a while to put a working base together here is an example client/server which works fine for me (python 3.6.5, pywin32 223 on Windows 10 Pro x64):Example output client
Example output server
Obviously you'd need some error checking around the various calls but that should work.
Additional side note: A colleague of mine ran into trouble with the pipe being closed the moment the client tried to perform I/O on it (exception claiming that "all pipe instances are busy"). It turned out that he was using
os.path.exists
in the client code to test whether the named pipe already existed before runningCreateFile
on it. This somehow breaks the pipe. So using the approach above (CreateFile
wrapped in a try-except) is the safe way of trying to connect to a pipe until it has been created by the server end.