Named Pipes between C# and Python

浪子不回头ぞ 提交于 2019-11-29 00:13:06

According to MS, ConnectNamedPipe is the "server-side function for accepting a connnection". That's why it never returns - it's waiting for a connection from a client. Here's some sample code showing C# as the server and python as the client:

C#:

NamedPipeServerStream server = new NamedPipeServerStream("Demo");
server.WaitForConnection();

MemoryStream stream = new MemoryStream();
using (BinaryWriter writer = new BinaryWriter(stream))
{
    writer.Write("print \"hello\"");
    server.Write(stream.ToArray(), 0, stream.ToArray().Length);
}

stream.Close();
server.Disconnect();
server.Close();

python:

import win32file
fileHandle = win32file.CreateFile("\\\\.\\pipe\\Demo", win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None)
left, data = win32file.ReadFile(fileHandle, 4096)
print data # prints \rprint "hello"

OK, I fixed the problem. I should seek to position 0 of buffer.

My Python code:

    win32file.WriteFile(CLIENT_PIPE,"%d\r\n"%i ,None)
    win32file.FlushFileBuffers(CLIENT_PIPE)
    win32file.SetFilePointer(CLIENT_PIPE,0,win32file.FILE_BEGIN)
    i,s = win32file.ReadFile(CLIENT_PIPE,10,None)

I think you are meant to use win32pipe.popen, not open.

Also try: pipe.flush(), pipe.read(), and time.sleep(0.01). Sometimes IPC takes a while to sync up.

I don't really know, that's my experience with the subprocess pipes. win32pipe might be different.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!