Python可以从Windows Powershell名为pipe的文件中读取吗?

2024-09-30 01:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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 )

现在,我需要一些Python代码片段从上面创建的命名管道中读取。Python能做到吗?在

提前谢谢!在


Tags: toionet管道isusewindowsrequired
1条回答
网友
1楼 · 发布于 2024-09-30 01:33:22

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

这是C代码

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
            }
        }
    }
}

下面是Python代码:

^{pr2}$

将C代码转换为.ps1文件。在

相关问题 更多 >

    热门问题