如何让Python脚本从dotnet core windows服务运行?
一点背景,如何让Python脚本从dotnet core windows服务运行?,python,c#,.net-core,microservices,ironpython,Python,C#,.net Core,Microservices,Ironpython,一点背景, 我有一个dotnetwindows服务,它需要一些来自Python脚本(main.py)的数据 main.py,它使用多个模块,包括numpy、scipy和其他第三方模块, 负责做一些目前用C语言无法完成的逻辑计算# main.py接受少量参数并返回一些结果,然后由我们的dotnet windows服务使用这些参数 我正在使用Python v3.8 现在,我正在努力想出一个解决方案,让dotnetwindows服务和python脚本一起工作。有人建议使用IronPython,但我
- 我有一个dotnetwindows服务,它需要一些来自Python脚本(main.py)的数据
- main.py,它使用多个模块,包括numpy、scipy和其他第三方模块, 负责做一些目前用C语言无法完成的逻辑计算#
- main.py接受少量参数并返回一些结果,然后由我们的dotnet windows服务使用这些参数
- 我正在使用Python v3.8
我希望并欢迎任何建议、建议或问题。添加类似此方法的内容:
public class YourClass
{
public string Run(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "python";
start.Arguments = string.Format("\"{0}\" \"{1}\"", cmd, args);
start.UseShellExecute = false;// Do not use OS shell
start.CreateNoWindow = true; // We don't need new window
start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
return result;
}
}
}
}
然后,在那里调用python文件,如下所示:
var res = new YourClass().Run("your_python_file.py","params");
Console.WriteLine(res);
Ironpython与Python 2.7兼容。Python3支持还有很长的路要走。如果您使用的是numpy和scipy,我肯定会选择微服务路线,这样您就可以使用当前受支持的版本
既然您的C#正在调用RESTAPI,那么python服务需要在Windows上运行吗?您可以在运行WSL的linux机器或Windows上运行吗 我还没有研究这些影响/限制。目前,建议的微服务将在Windows上运行,与上述dotnet Windows服务相同。有什么我应该注意的吗?谢谢@WombatPMIf如果您不在生产环境中,我会安装Apache或NGINX并避免使用IIS来运行微服务。如果我在生产环境中?在这种情况下,你有什么建议?这取决于运营团队,假设你有一个。具有标准监控、日志记录和报告功能的Ops团队通常希望Widows Box上的服务在IIS下运行。如果你没有这样的要求,那么你可以随心所欲。多年来,我使用Apache和桌面设备运行了一个仅限内部使用的API。参考上面的示例,假设您的_python_file.py中的脚本需要一些第三方模块才能运行。如何导入第三方模块?您的_python_file.py是否应该在特定环境中运行?我认为这些模块应该在运行_python_file.py之前安装好。谢谢Abdus