如何获取Python脚本返回值以在visualstudio窗体中使用?

2024-05-21 03:51:11 发布

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

我目前正在我的Raspberry Pi上使用一个DAQC2管板,并在上面测试模拟输入。为了获得输入,我调用python脚本来返回它们。我的问题是,我正在使用visualstudio创建一个表单GUI,这样当程序在Pi上独立运行时,表单就会处理GUI(在7英寸触摸屏上运行)

我目前已经尝试使用StreamReader,它在每次计时器计时时读取脚本的输出,然后更新标签

我的PythonScript类

    public PythonScript(string scriptName)
    {
        _scriptName = scriptName;
    }
    public string Run()
    {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "python3";
        psi.Arguments = _scriptName;
        psi.UseShellExecute = false;
        psi.CreateNoWindow = true;
        psi.RedirectStandardOutput = false;
        psi.RedirectStandardError = true;

        Process process = new Process();
        process.StartInfo = psi;
        process.StartInfo.RedirectStandardOutput = true;
        process.Start();

        StreamReader myStreamReader = process.StandardOutput;
        string str = myStreamReader.ReadLine();
        process.WaitForExit();
        process.Close();
        return str;

    }

我目前在Form1.cs类中的工作,该类处理窗体加载和计时器的位置

    private void Form1_Load(object sender, EventArgs e)
    {
        /**
        //Maximize form to fill screen
        WindowState = FormWindowState.Normal;
        FormBorderStyle = FormBorderStyle.None;
        Location = new Point(0, 0);
        TopMost = true;
        Screen currentScreen = Screen.FromHandle(this.Handle);
        this.Size = new System.Drawing.Size(currentScreen.Bounds.Width, currentScreen.Bounds.Height);
        **/

        //set up timer
        timer.Interval = (10);
        timer.Tick += new EventHandler(timer_tick);
        timer.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        string value = "";
        PythonScript getValue1 = new PythonScript("/home/pi/Desktop/DAQC2_Script.py");
        value = getValue1.Run();
        label1.Text = value;
    }

我的python脚本

    import piplates.DAQC2plate as x
    value = str(x.getADC(0, 1))
    return value

目前,我的表单构建和运行正常,但它没有做任何事情。标签仍然是默认的“00.0”。我确信我的RaspberryPi和它的设备连接正确,因为我可以执行脚本(没有return语句),它读取数据并允许我打印到控制台

我只是希望python脚本中的value每秒更新到label1.Text。我不仅是c#新手,而且对python也是新手,因此非常感谢您的帮助


Tags: 脚本true表单newstringreturnvaluepi
1条回答
网友
1楼 · 发布于 2024-05-21 03:51:11

因此,经过一段时间的挖掘,我彻底忽略了我的问题可能在我的python脚本中。我终于想到了使用process.RedirectStandardError,这让我发现我的“return”语句是“函数外的”,不仅我的return语句不在任何特定函数中,而且我发现它根本不需要。StreamReader处理读取而不使用脚本中的任何return语句。这对这个笨蛋来说是一次学习的经历

相关问题 更多 >