python - Python 可以从 Windows Powershell 命名管道中读取数据吗?

标签 python windows powershell named-pipes

我在 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 可以做到吗?

提前致谢!

最佳答案

礼貌: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 代码:

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)

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

关于python - Python 可以从 Windows Powershell 命名管道中读取数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20726600/

相关文章:

python - 使用外键创建多个对象

c++ - 检查 CWinApp 是否存在

powershell - 在 Powershell 中使用自定义用户文件夹创建本地用户

powershell - 如何使用 PowerShell 删除文件上的只读属性?

python - Tkinter 无法正确关闭并启动新文件

python - 如何覆盖 Sklearn 的 TSNE 以在 Pipeline 函数中使用?

python - 如何检查一个字符串是否是其他字符串的串联,并在python中的每个字符串之间插入一个字符

c++ - Qt - 4.7.3 - 如何进行静态构建

mysql - 在 Windows 上对 mysql 进行基准测试

powershell 计算文件夹中的文件并创建带有文件名结果的文本文件