Пустой консольный вывод при запуске .py из приложения C # - PullRequest
1 голос
/ 08 ноября 2019

Я пытаюсь запустить скрипт Python из моего приложения на C #.

Я прочел здесь множество тем и соединил следующий код:

private void RunPythonScript(string py1, string py2)
{
    try
    {
        ProcessStartInfo start = new ProcessStartInfo
        {
            FileName = py1,
            Arguments = py2,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                string stderr = process.StandardError.ReadToEnd();
                Console.Write(stderr);
                Console.Write(result);
            }
        }
    }
    catch (Exception ex)
    {
        Helpers.ReturnMessage(ex.ToString());
    }
}

private void RunPythonScriptToolStripMenuItem_Click(object sender, EventArgs e)
{
    string py1 = @"C:\Users\Graham\AppData\Local\Programs\Python\Python37-32\python.exe";
    string py2 = @"C:\Users\Graham\Desktop\Files\programming\PaydayDreamsProgramming\Python\scripts\domain-seo-analyzer\domain_seo_analyzer.py";
    RunPythonScript(py1, py2);
}

Это выглядит довольно просто.

Проблема в том, что консоль python.exe выскакивает пусто, поэтому я предполагаю, что скрипт не запущен. Нет ошибок, из которых я могу выйти, просто пустое поле консоли.

Есть ли что-то в моем коде, который я пропустил? (Я предполагаю, что это ошибка C #) оба пути к .exe и .py абсолютно верны.

Я не уверен, что еще нужно проверить, любая помощь будет оценена.

1 Ответ

0 голосов
/ 08 ноября 2019

Класс CommandLineProcess - запускает процесс командной строки и ожидает его завершения. Все стандартные выходные данные / ошибки фиксируются, и отдельное окно для процесса не запускается:

using System;
using System.Diagnostics;
using System.IO;

namespace Example
{
    public sealed class CommandLineProcess : IDisposable
    {
        public string Path { get; }
        public string Arguments { get; }
        public bool IsRunning { get; private set; }
        public int? ExitCode { get; private set; }

        private Process Process;
        private readonly object Locker = new object();

        public CommandLineProcess(string path, string arguments)
        {
            Path = path ?? throw new ArgumentNullException(nameof(path));
            if (!File.Exists(path)) throw new ArgumentException($"Executable not found: {path}");
            Arguments = arguments;
        }

        public int Run(out string output, out string err)
        {
            lock (Locker)
            {
                if (IsRunning) throw new Exception("The process is already running");

                Process = new Process()
                {
                    EnableRaisingEvents = true,
                    StartInfo = new ProcessStartInfo()
                    {
                        FileName = Path,
                        Arguments = Arguments,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                    },
                };

                if (!Process.Start()) throw new Exception("Process could not be started");
                output = Process.StandardOutput.ReadToEnd();
                err = Process.StandardError.ReadToEnd();
                Process.WaitForExit();
                try { Process.Refresh(); } catch { }
                return (ExitCode = Process.ExitCode).Value;
            }
        }

        public void Kill()
        {
            lock (Locker)
            {
                try { Process?.Kill(); }
                catch { }
                IsRunning = false;
                Process = null;
            }
        }

        public void Dispose()
        {
            try { Process?.Dispose(); }
            catch { }
        }
    }
}

Затем используйте его так:

private void RunPythonScriptToolStripMenuItem_Click(object sender, EventArgs e)
{
    string pythonPath = @"C:\Users\Graham\AppData\Local\Programs\Python\Python37-32\python.exe";
    string script = @"C:\Users\Graham\Desktop\Files\programming\PaydayDreamsProgramming\Python\scripts\domain-seo-analyzer\domain_seo_analyzer.py";

    string result = string.Empty;

    using (CommandLineProcess cmd = new CommandLineProcess(pythonPath, script))
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine($"Starting python script: {script}")

        // Call Python:
        int exitCode = cmd.Run(out string processOutput, out string processError);

        // Get result:
        sb.AppendLine(processOutput);
        sb.AppendLine(processError);
        result = sb.ToString();
    }

    // Do something with result here
}

Держите меня в курсе, если по-прежнему возникают ошибки.

...