3

I'm wondering if it's possible to kill a python script using C#.

In the small application I'm currently developing, a python application launches to localhost:portnumber. The portnumber of the application is always the same.

Is it possible, when the application is already running (I'm checking that by getting a list of ports currently in use), to kill it using some sort of command?

I've already found out that, in case it is not running, I can start the application using Process.Start();

2
  • which os is supposed to work? Commented Feb 6, 2013 at 23:09
  • I'm primarily developing it for Windows (hence the C# :P) Commented Feb 6, 2013 at 23:09

1 Answer 1

1

You can use Process.Kill() to kill a specific process...
To find out which process to kill you can use GetProcesses() and itterate through them...

For example, here is how you can kill the calculator (calc.exe):

 foreach (Process process in Process.GetProcesses().Where(p => 
                                                         p.ProcessName == "calc"))
 {
     process.Kill();
 }

This will find all processes named "calc" and kill them.

In your case, If you already have a Process object (because you called Process.Start() ) you can specifically kill that one using the Kill() method.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply, however the process(es) that started are both listed as 'pythonw.exe' in the taskmanager. There is no distinction between them aside the port number they are listening to. Would the above example still work then?
Almost, since you'll need the distinct Id property of the process. Here is an example of how to get the ProcessId based on the open port. You can use that and the example above to get what you want. (You'll want to use p.Id instead of p.ProcessName)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.