Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of using C # to guard the Python process

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What is the method of using C # to guard the Python process? in order to solve this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.

Background

At present, one of the projects I am mainly responsible for is the client development of the CCMUP S architecture, the front end is mainly realized through WPF related technologies, the back end is realized through Python, and the data communication between the front and back end is processed through MQ. Because the Python process needs to rely on the client process to run, in order to ensure the stability of the back-end business process, it is necessary to guard the Python process through a daemon to prevent it from exiting due to unknown reasons. Here is a brief record of one of my implementations.

Implement #

For our system, only one Python process is allowed, so the corresponding service type should adopt singleton mode. This part of the code is relatively simple, so it is posted directly. The sample code is as follows:

Public partial class PythonService {private static readonly object _ locker = new object (); private static PythonService _ instance; public static PythonService Current {get {if (_ instance = = null) {lock (_ locker) {if (_ instance = = null) {_ instance = new PythonService ();} return _ instance;}} private PythonService () {}}

Create a standalone process #

As the back-end Python code needs to install some third-party extension libraries, for convenience, we use the way to summarize the python installation files and extension packages and their code packaged into our project directory, and then create a Python process, in this process by setting environment variables for the Python process to do some environment configuration. The sample code is as follows:

Public partial class PythonService {private string _ workPath = > Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "scripts"); private string _ pythonPath = > Path.Combine (_ workPath, "python27"); private bool isRunning = false; private int taskPID =-1; public void Start () {taskPID = CreateProcess (); isRunning = taskPID! =-1; var msg = isRunning? "Service startup failed...": "Service startup failed..."; Trace.WriteLine (msg);} public void Stop () {KillProcessAndChildren (taskPID); isRunning = false; taskPID =-1;} private int CreateProcess () {KillProcessAndChildren (taskPID); int pid =-1; var psi = new ProcessStartInfo (Path.Combine (_ pythonPath, "python.exe")) {UseShellExecute = false, WorkingDirectory = _ workPath, ErrorDialog = false}; psi.CreateNoWindow = true; var path = psi.EnvironmentVariables ["PATH"] If (path! = null) {var array = path.Split (new [] {';'}) .Where (p = >! p.ToLower (). Contains ("python")) .ToList (); array.AddRange (new [] {_ pythonPath, Path.Combine (_ pythonPath, "Scripts"), _ workPath}); psi.EnvironmentVariables ["PATH"] = string.Join (";", array);} var ps = new Process {StartInfo = psi} If (ps.Start ()) {pid = ps.Id;} return pid;} private static void KillProcessAndChildren (int pid) {/ / Cannot close 'system idle process'. If (pid {while (! token.IsCancellationRequested) {var has = Process.GetProcesses (). Any (p = > p.Id = = taskPID); Trace.WriteLine ($"MQ status: {DateTime.Now}-{has}"); if (! has) {taskPID = CreateProcess (_ reqhost, _ subhost, _ debug); isRunning = taskPID > 0; var msg = isRunning? "MQ restart succeeded": "MQ restart failed, waiting for next restart"; Trace.WriteLine ($"MQ status: {DateTime.Now}-{msg}");} Thread.Sleep (2000);}, token);}}

Here I am using Thread.Sleep (2000) to continue thread waiting, you can also use await Task.Delay (2000 token), but using this method will generate a TaskCanceledException exception when sending a cancellation request. So in order not to generate unnecessary abnormal information, I adopted the first solution.

Next, refine our Start and Stop methods, with the sample code as follows:

Public void Start () {taskPID = CreateProcess (); isRunning = taskPID! =-1; if (isRunning) {cts = new CancellationTokenSource (); StartWatch (cts.Token);} var msg = isRunning? "Service started successfully...": "Service startup failed..."; Trace.WriteLine (msg);} public void Stop () {cts?.Cancel (false); cts?.Dispose (); KillProcessAndChildren (taskPID); taskPID =-1; isRunning = false;}

Finally, the upper layer call is relatively simple, just call the Start method and the Stop method directly.

Summary

In our actual project code, the PythonService code is a little more complex than the above code, and we have added a message queue for MQ internally. So for the convenience of demonstration, I only list the core code related to this article. In the specific use process, we can process it according to an implementation method provided in this article.

This is the answer to the question about how to use C # to guard the Python process. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report