简体   繁体   English

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

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

I'm executing a Python script from my C# console application. 我正在从我的C#控制台应用程序执行Python脚本。 I made a bare solution which executes a script and solely prints a string to the output. 我做了一个简单的解决方案,它执行一个脚本并只输出一个字符串到输出。

The Python initialization seems to take some time (about .5 second) which is quite annoying if i would like to run this code in some iterating code. Python初始化似乎需要一些时间(大约0.5秒),如果我想在一些迭代代码中运行此代码,这非常烦人。

Is it possible to somehow re-use the created process so Python doesn't need to re-initialize? 是否有可能以某种方式重用已创建的进程,因此Python不需要重新初始化? (ps IronPython is not an option due to missing libraries) (由于缺少库,ps IronPython 不是一个选项)

I'm using the following code to execute the script (this code runs in a for loop, 25 iterations takes about 10 seconds to run in total...): 我正在使用以下代码来执行脚本(此代码在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
            }
        }

It is possible to create a restful service in python, that receives a command or a script as a string, and executes it (using exec). 可以在python中创建一个restful服务,它接收一个命令或脚本作为字符串,然后执行它(使用exec)。

This solution actually creates a remote python shell, which is much faster than creating a new process for every command. 这个解决方案实际上创建了一个远程python shell,比为每个命令创建一个新进程要快得多。

This can also help you enable a stateful execution. 这也可以帮助您启用有状态执行。 In other words, any side effects your command causes, such as variable declaration, imports etc', will remain when you request more command executions from the server. 换句话说,当您从服务器请求更多命令执行时,您的命令导致的任何副作用(例如变量声明,导入等)将保留。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM