c# - 从 C# 应用程序运行 .py 时控制台输出空白

标签 c# python console

我想要做的是从我的 C# 应用程序运行 Python 脚本。

我在这里阅读了很多线程,并将以下代码放在一起:

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 的路径都完全正确。

我不确定还需要检查什么,任何帮助将不胜感激。

最佳答案

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
}

如果仍然出现错误,请随时通知我。

关于c# - 从 C# 应用程序运行 .py 时控制台输出空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771825/

相关文章:

c# - 为什么XNA Write/ReadObject <Model>()不保留顶点/索引缓冲区数据?

python - 抓取需要登录的网站

python - 如何动态地将谓词传递给过滤函数?

c# - 在 Mono Linux 上使用 SerialPort 时出现高波特率错误

c# 将 console.writeline 转换为字符串

c# - 如何解决连接字符串异常(本地数据库C#)

c# - FakeItEasy - 是否可以拦截一个方法并将其替换为我自己的实现?

java - 编码控制台俄语 sumbols 输入

scala - 如何编写 consolePatternMatchListener 扩展点?

c# - 如何验证一个类型是否重载/支持某个运算符?