Search code examples
pythonprocesstermination

Killing processes via python


my knowledge of python is rather limited so I might just be poking in the dark...

What I am attempting to do is open a file, write some stuff in it and close it.

The problem I have is, what if that file is opened?

To fit my needs, it needs to be closed, no matter what's happening to it, so I can open it via python application.

So if I cant open a file that's open, I can try to force close it and then open it via python?

Found this lib: https://psutil.readthedocs.io/en/latest/

It kind of does what I want, maybe I'm just missing on the how.

It currently returns me a list of all processes and gives me ids that I can use to kill processes.(find_procs_by_name, kill_proc_tree)

While in reality, I would like to close test.csv that is open in excel instead of closing all of excel, any ideas how I can achieve that?


Solution

  • You can use pgrep as if it was a shell command.

    https://pypi.org/project/pgrep/

    Get your ID through conditionals and then kill it as Andrew said.

    Regards!

    EDIT:

    Another approach using psutils with a loop loking for a process given a name:

    import psutil
    # Get all proces in a list
    pids = psutil.pids()
    print("There is", len(pids), "Process")
    
    #Search process with this string
    name_like = "evolution"
    
    # Loop checking for the pid "name_like"
    i = 0
    while i<len(pids):
        print("i is", i)
        print("pid (pids[i]) is", pids[i])
        print("Proces name is", psutil.Process(pid=pids[i]).name())
        if name_like in psutil.Process(pid=pids[i]).name():
            print("KILL THIS F@*!& PROCESS")
        i+=1
    

    This is the output:

    i is 181
    pid (pids[i]) is 1834
    Proces name is evolution-calendar-factory
    KILL THIS F@*!& PROCESS
    

    Regards.