Skip to content
Advertisement

How to terminate process from Python using pid?

I’m trying to write some short script in python which would start another python code in subprocess if is not already started else terminate terminal & app (Linux).

So it looks like:

JavaScript

Have problem of lacking knowledge to name proces by pid which app reads from file “.proc”. The other problem is that interpreter says that string named dat is not equal to “x” ??? What I’ve missed ?

Advertisement

Answer

Using the awesome psutil library it’s pretty simple:

JavaScript

If you don’t want to install a new library, you can use the os module:

JavaScript

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

JavaScript

Sample run:

JavaScript

Note: In previous psutil versions cmdline was an attribute instead of a method.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement