简体   繁体   中英

Running a python script in a windows service application (no user logged on)

Running a python script (developed in an other department) by a C# Windows Service application.

I wrote a console application which executes a python script. Now I tried to transform the console app into a Windows Service. The Windows Service is working without the script propper (loggin in event log). The service stopped at the point of starting ProcessStartInfo.

public string Run()
        {
            _pySkript.WorkingDirectory = _workinDirectory;
            _pySkript.FileName = _pythonPath;
            _pySkript.Arguments = string.Format("{0} {1} {2} {3} {4} {5} {6}", a, b, c, d, e, f, g);
            _pySkript.UseShellExecute = false;
            _pySkript.RedirectStandardOutput = true;
            _pySkript.CreateNoWindow = true;
            _pySkript.RedirectStandardError = true;
            _pySkript.RedirectStandardInput = true;
            _pySkript.ErrorDialog = false;
            _pySkript.WindowStyle = ProcessWindowStyle.Hidden;

            using (Process process = Process.Start(_pySkript))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    OnScriptRunFinished();
                    return result;
                }
            }
        }

Thank you to @BugFinder for his support. At the end it was a spelling mistake.

Example solution:

First project: Logic.csproj

using System;
using System.Diagnostics;
using System.IO;

namespace Logic
{
public class RunScript
{
    string _parameterString = string.Format("{0} {1} {2} {3}","main.py", "Testuser", "TestPw", "MyEnviroment");
    string _resultCon;
    public string Start()
    {
        ProcessStartInfo _pySkript = new ProcessStartInfo();

        _pySkript.WorkingDirectory = @"D:\GitRepos\ScriptRunner\PyScript\";
        _pySkript.FileName = "python";
        _pySkript.Arguments = _parameterString;
        _pySkript.UseShellExecute = false;
        _pySkript.RedirectStandardOutput = true;
        _pySkript.CreateNoWindow = true;
        _pySkript.RedirectStandardError = true;
        _pySkript.RedirectStandardInput = true;
        _pySkript.ErrorDialog = false;
        _pySkript.WindowStyle = ProcessWindowStyle.Hidden;

        try
        {
            using (Process process = Process.Start(_pySkript))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    _resultCon = reader.ReadToEnd();
                }
            }
        }
        catch (Exception ex)
        {
            _resultCon = ex.ToString();
        }
        return _resultCon;
    }
  }
}

Second project: ScriptRunner.csproj

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic;

namespace ScriptRunner
{
class Program
{
    static void Main(string[] args)
    {
        var runMyScript = new RunScript();
        Console.WriteLine(runMyScript.Start());
    }
  }
}

Third project: ScriptRunnerService.csproj

using System.Diagnostics;
using System.ServiceProcess;
using Logic;

namespace ScriptRunnerService
{
public partial class ScriptRunService : ServiceBase
{
    public ScriptRunService()
    {
        InitializeComponent();
        eventLog1 = new EventLog();
        if (!EventLog.SourceExists("MySource"))
        {
            EventLog.CreateEventSource(
                "MySource", "MyNewLog");
        }
        eventLog1.Source = "MySource";
        eventLog1.Log = "MyNewLog";

        var runMyScript = new RunScript();
        var output = runMyScript.Start();
        eventLog1.WriteEntry(output.ToString(), EventLogEntryType.Information);
    }

    protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("In OnStart.", EventLogEntryType.Information);
    }

    protected override void OnStop()
    {
        eventLog1.WriteEntry("In OnStop.", EventLogEntryType.Information);
    }
  }
}

Install Service:

You need InstallUtil.exe to install the service!

installutil -i ScriptRunnerService.exe

Windows-Key: r services.msc -> Start Service eventvwr.msc -> Check Logs

Uninstall Service:

installutil -u ScriptRunnerService.exe

Finde complete solution incl. python script on GitHub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM