我正在从我的 C# 控制台应用程序中执行 Python 脚本。我做了一个简单的解决方案,它执行一个脚本并只在输出中打印一个字符串。
Python 初始化似乎需要一些时间(大约 0.5 秒),如果我想在一些迭代代码中运行这段代码,这会很烦人。
是否有可能以某种方式重新使用创建的进程,这样 Python 就不需要重新初始化? (附注:IronPython 不是一个选项,因为缺少库)
我正在使用以下代码来执行脚本(此代码在 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,这比为每个命令创建一个新进程要快得多。
这还可以帮助您启用有状态执行。换句话说,当您从服务器请求更多命令执行时,您的命令引起的任何副作用(例如变量声明、导入等)都将保留。
关于c# - 可以通过重用进程更快地完成 Python 脚本的 C# 执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28322932/