Python 脚本的 C# 执行是否可以通过重用进程更快地完成?

Can C# execution of Python script be done faster by re-using process?

我正在从我的 C# 控制台应用程序中执行 Python 脚本。我做了一个简单的解决方案,它执行一个脚本并只在输出中打印一个字符串。

Python 初始化似乎需要一些时间(大约 .5 秒),如果我想 运行 在某些迭代代码中使用此代码,这会很烦人。

是否有可能以某种方式重新使用创建的进程以便 Python 不需要重新初始化? (p.s.IronPython 不是一个选项,因为缺少库)

我正在使用下面的代码来执行脚本(此代码 运行s 在一个 for 循环中,25 次迭代总共需要大约 10 秒到 运行.. .):

        string cmd = @"Python/test.py";
        string args = "";
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = @"C:\ex\programs\Python27\python.exe";
        start.Arguments = string.Format("{0} {1}", cmd, args);
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result); //output works
            }
        }

可以在 python 中创建一个 restful 服务,它接收命令或脚本作为字符串,并执行它(使用 exec)。

这个解决方案实际上创建了一个远程 python shell,这比为每个命令创建一个新进程要快得多。

这也可以帮助您启用有状态执行。换句话说,当您从服务器请求更多命令执行时,您的命令引起的任何副作用(例如变量声明、导入等)都将保留。