![]() |
Killing processes via python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Killing processes via python (/thread-27652.html) |
Killing processes via python - Lavina - Jun-15-2020 Hello, 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. 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? RE: Killing processes via python - DeaD_EyE - Jun-16-2020 Usually my answer to this is: Don't ask for permission, ask for forgiveness. But your problem is different. I guess program A is writing something to file A and afterwards program B should work with file A or vice versa. One little trick to ship around this problem is renaming. First you write your data to some_name.txt.0 .When everything is done and the file is closed, then the program should rename the file to some_name.txt .The second program is not allowed to open the *.0 file. Here a fuser example for psutil: def fuser(file): for proc in psutil.process_iter(): try: for open_file in proc.open_files(): if file == open_file.path: print(proc.pid, open_file.path) except psutil.AccessDenied: passBut this check does not guarantee, that after the function call the file is still not in in use. On Linux exists also the command fuser which is used to look which PIDs accessing a file.The Linux command lsof is also capable of this, but could also list open network sockets. RE: Killing processes via python - warnerarc - Aug-04-2021 It is better you can use the multiprocessing module which is almost the same and it has terminate() function for killing a processes. Here, to kill a process , you can simply call the method: yourProcess.terminate() # kill the process! Python will kill your process (on Unix through the SIGTERM signal, while on Windows through the TerminateProcess() call). Pay attention to use it while using a Queue or a Pipe! (it may corrupt the data in the Queue/Pipe) |