ozgur
ozgur

Reputation: 2719

How to inform C# code when executable created using PyInstaller exits?

Similar questions are answered for linux, but I couldn't find for windows. I have a Python script as follows:

import sys
import os

#do something

# sys.exit(0) used this one, as well
os._exit(0)

which I convert to windows executable using PyInstaller. And the C# code is:

var process = new System.Diagnostics.Process();
process.StartInfo = new System.Diagnostics.ProcessStartInfo(path, "Long Argument");
process.Exited += (s, e) => { Console.WriteLine("Process Finished"); }; ;
process.Start();
process.WaitForExit();

The process starts and runs correctly. But when it exits Exited event is not raised. I am also not sure in which side I am doing it wrong, C# or python.

Upvotes: 1

Views: 236

Answers (1)

MethodMan
MethodMan

Reputation: 18863

You need to have an event for Process.Exited explained here Process.Exited Event

based on this coded portion of the example you are missing EnableRaisingEvents should be set to true

private Process myProcess = new Process();
private int elapsedTime;
private bool eventHandled;

// Print a file with any known extension.
public void PrintDoc(string fileName)
{

    elapsedTime = 0;
    eventHandled = false;

    try
    {
        // Start a process to print a file and raise an event when done.
        myProcess.StartInfo.FileName = fileName;
        myProcess.StartInfo.Verb = "Print";
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.EnableRaisingEvents = true;
        myProcess.Exited += new EventHandler(myProcess_Exited);
        myProcess.Start();

    }
    catch (Exception ex)
    {
        Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
        return;
    }

    // Wait for Exited event, but not more than 30 seconds.
    const int SLEEP_AMOUNT = 100;
    while (!eventHandled)
    {
        elapsedTime += SLEEP_AMOUNT;
        if (elapsedTime > 30000)
        {
            break;
        }
        Thread.Sleep(SLEEP_AMOUNT);
    }
}

Upvotes: 1

Related Questions