асинхронный интерфейс для скрипта Python - PullRequest
0 голосов
/ 25 мая 2018

Я создал интерфейс winform для моей программы на python, моя программа на python представляет собой голосовой помощник в реальном времени, и мне нужен интерфейс, который должен реагировать мгновенно, когда python выдает выходные данные.Мне нужно отобразить стандартный вывод на интерфейс мгновенно.нижеприведенная программа - это то, что я сделал.

в этом коде интерфейс не отвечает должным образом.Программа python выполняется в фоновом режиме непрерывно и не реагирует на голос.Мне нужна программа, которая выполняет мою программу на Python и отображает стандартный вывод в интерфейс winform.

namespace @interface
{
    public partial class Form1 : Form
    {
        public static string text;
        public Form1()
        {
            InitializeComponent();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private async void start_button_Click(object sender, EventArgs e)
        {
            string line;
            int counter=0;
            msg.Text = "Hey, Tell me something!";

            Task task = new Task(Execute);
            task.Start();

        }


           public void Execute()
            {
                // full path of python interpreter 
                string python = @"C:/Users/Jayasooryan/AppData/Local/Programs/Python/Python36-32/python.exe";

                // python app to call 
                string myPythonApp = @"C:/Users/Jayasooryan/AppData/Local/Programs/Python/Python36-32/Avira.py";

                // Create new process start info 
                ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);

                // make sure we can read the output from stdout 
                myProcessStartInfo.UseShellExecute = false;
                myProcessStartInfo.RedirectStandardOutput = true;
                myProcessStartInfo.CreateNoWindow = true;

                // start python app with 3 arguments  
                // 1st arguments is pointer to itself,  
                // 2nd and 3rd are actual arguments we want to send 
                myProcessStartInfo.Arguments = myPythonApp;

                Process myProcess = new Process();
                // assign start information to the process 
                myProcess.StartInfo = myProcessStartInfo;

                // start the process 
                myProcess.Start();

                // Read the standard output of the app we called.  
                // in order to avoid deadlock we will read output first 
                // and then wait for process terminate: 
                StreamReader myStreamReader = myProcess.StandardOutput;
                string myString = myStreamReader.ReadLine();
                text = myString;


            //Console.WriteLine(myString);

            /*if you need to read multiple lines, you might use: 
                string myString = myStreamReader.ReadToEnd() */

            // wait exit signal from the app we called and then close it. 
            myProcess.WaitForExit();
            myProcess.Close();

            // write the output we got from python app 

            //Console.ReadLine();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

1 Ответ

0 голосов
/ 25 мая 2018

Во-первых: вы не должны пытаться прочитать одну строку из процесса python, а вместо этого использовать событие OutputDataReceived, которое запускается, когда процесс записывает новые данные.

Second: поскольку выходные данные буферизуются, вы, вероятно, захотите сбросить их после записи в процессе Python.

Итак, вот простой сценарий Python, который продолжает запись в стандартный вывод (обратите внимание, как вызывается stdout.flush):

import random
import time
import sys

while True:
   rand = random.randint(1, 10)
   time.sleep(1)
   print rand
   sys.stdout.flush()
   if rand in (9, 10):
       break

А вот простая форма, которая читает вывод этого самого сценария:

var f = new Form();
var t = new TextBox();
t.Dock = DockStyle.Fill;
t.Multiline = true;
f.Controls.Add(t);
f.Load += (s, e) => {
    Process process = new Process();
    process.StartInfo.FileName = "python";
    process.StartInfo.Arguments = @"d:\script.py";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.OutputDataReceived += (s2, e2) => {
        t.Text += e2.Data + Environment.NewLine;
    };
    process.Start();
    process.BeginOutputReadLine();
};
f.ShowDialog();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...