【问题标题】:Transfer variables from Python to C#将变量从 Python 传输到 C#
【发布时间】:2021-06-01 19:24:58
【问题描述】:

我正在使用 OpenCV-Python 和 GUI C#(Winform) 制作一个项目。我想在 python 中保存一个变量“数据”并将其写入 txt 文件。然后通过从 c# 运行 python 脚本将其传输到 GUI C# 并从 txt 文件中读取“数据”的值。 但是我遇到了问题:当我更改“数据”的值并按下按钮 1 时,它没有立即显示“数据”的值。它只是显示了“数据”的先前值,我不得不再按 2 次。然后就可以正常显示了。 请告诉我该怎么做。 我的 Python 代码:

import numpy as np
import cv2

file = open("D:\\Data\\VisualStudio2019\\python-cs\\pytocs.txt","w")
cap = cv2.VideoCapture(1)

while True:
    # Capture frame-by-frame
    ret, frame = cap.read()

    data = "123"
    file.write(data + "\n")
    

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        file.close()
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

我的 C# 代码:

private void button1_Click(object sender, EventArgs e)
        {
            RunPython();
            timer1.Enabled = true;
        }
static void RunPython()
        {

            var psi = new ProcessStartInfo();
            psi.FileName = @"C:\Users\tramn\AppData\Local\Programs\Python\Python37\python.exe";

            var script = @"D:\Data\VisualStudio2019\python-cs\PythonApplication1\pythontotext.py";
            psi.Arguments = $"\"{script}\"";

            // Process configuration
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;

            //Execute process and get output
            Process.Start(psi);
            
        }

private void timer1_Tick(object sender, EventArgs e)
        {
            using (var fs = new FileStream(@"D:\Data\VisualStudio2019\python-cs\pytocs.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var reader = new StreamReader(fs, System.Text.Encoding.Default))
            {

                string data = reader.ReadLine();
                textBox1.Text = data;
            }
        }

【问题讨论】:

    标签: python c# text-files opencv-python


    【解决方案1】:

    您的 python 进程和计时器几乎同时启动,因此 FileStream 可能在 python 写入文件行之前启动。

    并且感觉到您正在尝试继续阅读该文件,请查看此Timer.AutoReset 以使您的计时器不仅运行一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2016-03-29
      相关资源
      最近更新 更多