使用C#和python之间的管道发送和获取信号

问题描述

我用C#创建了管道服务器,而python将其连接。我用python创建一个csv文件,并通过管道将信号发送到C#代码。当我运行python代码时,创建csv文件及其标头。然后按f6键,然后开始填充csv文件值。用f7键停止填充。创建csv文件时,我使用管道发送消息,并且可以使用C#捕获此信号,但是我想在按f7键时捕获另一条消息而不是第一条消息。基本上,我更改了第一个信号变量值。它的名称是file_situation。当我按下f7键时,file_situation值的开头为b'Open',而file_situation的值必须更改为b'End'。当我尝试执行此操作时,出现OS错误:Invalid参数。我也无法使用C#捕获“结束”消息。因为当我尝试捕获“ End”信号时,第一个创建的信号“ Open”将作为参数发送给另一个函数。我应该连续阅读该信号。

我使用此事件使用C#创建服务器,并从python代码捕获消息。另外,我正在使用Thread连续捕获信号值。

private void Button1_Click(object sender,EventArgs e)
    {
        
        var server = new NamedPipeServerStream("NPtest");
        Console.WriteLine("Waiting for connection...");
        server.WaitForConnection();
        Console.WriteLine("Connected.");
        var br = new BinaryReader(server);
        var len = (int)br.ReadUInt32();            // Read string length
        var str = new string(br.ReadChars(len));

        plotThread = new Thread(() =>
        {
            while (true)
            {
                plotThread.Priority = ThreadPriority.Lowest;
                plotThread.IsBackground = true;
                StartReadingFile(str);

            }

        });

        plotThread.Start();
              
    }

这是StartReadingFile函数。我调用了另一个名为Readcsv的函数,并将管道信号作为参数发送。

 public void StartReadingFile(string file_situation)
    {
        LastCreatedFilePath read = new LastCreatedFilePath();
        Console.WriteLine(file_situation);
        if (file_situation != "End")
        {
            Console.WriteLine(read.NewPath);
            tempFilePath = read.NewPath;
            ReadCsv(tempFilePath,file_situation);
        }
        

        
    }

这是Python csv创建者代码管道。

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

file_situation = b'Open'
f.write(struct.pack('I',len(file_situation)) + file_situation)
f.seek(0)`

开始填充csv:

def start(key): #create csv file start condition also,it ends first listener to create file.

if key == keyboard.Key.f6:
    print('Exporting start...')
    return False # stop first listener for on_press

使用此功能填充csv结束。

def stop(key): #program stop condition. it actives when listener running condition breaks.

global temp_path1,file_situation
try:
    if key == keyboard.Key.f7:
        
        file_situation = b'End'
        f.write(struct.pack('I',len(file_situation)) + file_situation)
        f.seek(0)
        print ('Exporting stopped...')
        return False  

最后,我打算用'End'信号中断ReadCsv函数内部的while循环。

 if (file_situation == "End")
                    {
                        
                        Console.WriteLine("End of While!");
                        break;

                    }

如果您不理解,我可以更清楚地解释。谢谢您的时间。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...