1

I have the following named pipe created in Windows Powershell.

# .NET 3.5 is required to use the System.IO.Pipes namespace
[reflection.Assembly]::LoadWithPartialName("system.core") | Out-Null
$pipeName = "pipename"
$pipeDir = [System.IO.Pipes.PipeDirection]::InOut
$pipe = New-Object system.IO.Pipes.NamedPipeServerStream( $pipeName, $pipeDir )

Now, what i need is some Python code snippet to read from the above named pipe created. Can Python do that ?

Thanks in advance !

jfs
  • 399,953
  • 195
  • 994
  • 1,670
a4aravind
  • 1,202
  • 1
  • 14
  • 25
  • 1
    Have you tried `data = open(r'\\.\pipe\pipename', 'rb', 0).read()` in Python? – jfs Dec 22 '13 at 05:48
  • Thanks J.F, but my powershell namedpipe waitsforaconnection and when I start the .read() operation, the namedpipe somehow gets closed. Is there something else instead of read(), like connect() or something so that I just make a connection initially and then do the write-read operations. Correct me if I'm wrong – a4aravind Dec 22 '13 at 09:06
  • related: [Named Pipes between C# and Python](http://stackoverflow.com/q/1749001/4279) – jfs Dec 22 '13 at 09:27
  • 1
    Thanks J.F I have it working now. Thanks a lot. I'll copy the one which is working fine below – a4aravind Dec 23 '13 at 04:41

1 Answers1

4

Courtesy :http://jonathonreinhart.blogspot.com/2012/12/named-pipes-between-c-and-python.html

Here's the C# Code

using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
class PipeServer
{
    static void Main()
    {
        var server = new NamedPipeServerStream("NPtest");

        Console.WriteLine("Waiting for connection...");
        server.WaitForConnection();

        Console.WriteLine("Connected.");
        var br = new BinaryReader(server);
        var bw = new BinaryWriter(server);

        while (true)
        {
            try
            {
                var len = (int)br.ReadUInt32();            // Read string length
                var str = new string(br.ReadChars(len));    // Read string

                Console.WriteLine("Read: \"{0}\"", str);

                //str = new string(str.Reverse().ToArray());  // Aravind's edit: since Reverse() is not working, might require some import. Felt it as irrelevant

                var buf = Encoding.ASCII.GetBytes(str);     // Get ASCII byte array     
                bw.Write((uint)buf.Length);                // Write string length
                bw.Write(buf);                              // Write string
                Console.WriteLine("Wrote: \"{0}\"", str);
            }
            catch (EndOfStreamException)
            {
                break;                    // When client disconnects
            }
        }
    }
}

And here's the Python code:

import time
import struct

f = open(r'\\.\pipe\NPtest', 'r+b', 0)
i = 1

while True:
    s = 'Message[{0}]'.format(i)
    i += 1

    f.write(struct.pack('I', len(s)) + s)   # Write str length and str
    f.seek(0)                               # EDIT: This is also necessary
    print 'Wrote:', s

    n = struct.unpack('I', f.read(4))[0]    # Read str length
    s = f.read(n)                           # Read str
    f.seek(0)                               # Important!!!
    print 'Read:', s

    time.sleep(2)

Convert the C# code into a .ps1 file.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
a4aravind
  • 1,202
  • 1
  • 14
  • 25