簡體   English   中英

如何讓我的 Python 腳本從我的 dotnet 核心 windows 服務運行?

[英]How can I get my Python script to run from my dotnet core windows service?

一點背景,

  • 我有一個dotnet windows 服務,它需要來自 Python 腳本 (main.py) 的一些數據

  • main.py使用了多個模塊,包括numpy、scipy等第三方模塊,負責做一些目前在C#中無法完成的邏輯計算

  • main.py接受少量參數並返回一些結果,然后由我們的dotnet windows 服務使用

  • 我正在使用 Python v3.8

現在,我正在努力想出一個解決方案,讓 dotnet windows 服務和 python 腳本一起工作。 有使用IronPython的建議,但我認為它對導入 3rd 方模塊有限制,這在這種情況下可能不起作用。

I was thinking of using this main.py as a microservice ie a restful API using Flask probably by doing this my dotnet windows service will can make requests whenever it needs the python script to carry out the calculations, and it's scalable when it comes to using它在別處

否則,如果您認為可以采取不同的方式,請提出建議

我會喜歡並歡迎任何建議、建議或問題。

Ironpython 與 Python 2.7 兼容。 Python3 支持還有很長的路要走。 如果您使用的是 numpy 和 scipy,我肯定會使用 go 微服務路線,以便您可以使用當前受支持的版本。

So now that your C# is calling a REST API does the python service need to run on 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM