如何让Python脚本从dotnet core windows服务运行?

2024-04-26 00:36:58 发布

您现在位置:Python中文网/ 问答频道 /正文

一点背景,

  • 我有一个dotnetwindows服务,它需要一些来自Python脚本(main.py)的数据

  • main.py,它使用多个模块,包括numpy、scipy和其他第三方模块, 负责进行一些目前在C#

  • main.py接受少量参数并返回一些结果,然后由我们的dotnet windows服务使用这些参数

  • 我正在使用Python v3.8

现在,我正在努力想出一个解决方案,让dotnetwindows服务和python脚本一起工作。有人建议使用IronPython,但我相信它在导入第三方模块方面有限制,而第三方模块在这种情况下可能无法工作

我正在考虑使用这个main.py作为一个微服务即一个使用Flask的restful API。也许通过这样做,我的dotnet windows服务可以在需要python脚本执行计算时发出请求,并且在其他地方使用它时是可伸缩的

否则,如果您认为可以采用不同的方法,请提供建议

我希望并欢迎任何建议、建议或问题


Tags: 模块数据pynumpy脚本参数mainwindows
2条回答

Ironpython与Python 2.7兼容。Python3支持还有很长的路要走。如果您使用的是numpy和scipy,我肯定会选择微服务路线,这样您就可以使用当前受支持的版本

既然您的C#正在调用RESTAPI,那么python服务需要在Windows上运行吗?您可以在运行WSL的linux机器或Windows上运行吗

添加类似于此方法的内容:

     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);

相关问题 更多 >