Issue
I want to close some files like .txt, .csv, .xlsx that I have opened using os.startfile().
I know this question asked earlier but I did not find any useful script for this.
I use windows 10 Environment
Solution
I believe the question wording is a bit misleading - in reality you want to close the app you opend with the os.startfile(file_name)
Unfortunately, os.startfile
does not give you any handle to the returned process.
help(os.startfile)
startfile returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application's exit status.
Luckily, you have an alternative way of opening a file via a shell:
shell_process = subprocess.Popen([file_name],shell=True)
print(shell_process.pid)
Returned pid is the pid of the parent shell, not of your process itself. Killing it won't be sufficient - it will only kill a shell, not the child process. We need to get to the child:
parent = psutil.Process(shell_process.pid)
children = parent.children(recursive=True)
print(children)
child_pid = children[0].pid
print(child_pid)
This is the pid you want to close. Now we can terminate the process:
os.kill(child_pid, signal.SIGTERM)
# or
subprocess.check_output("Taskkill /PID %d /F" % child_pid)
Note that this is a bit more convoluted on windows - there is no os.killpg
More info on that: How to terminate a python subprocess launched with shell=True
Also, I received PermissionError: [WinError 5] Access is denied
when trying to kill the shell process itself with os.kill
os.kill(shell_process.pid, signal.SIGTERM)
subprocess.check_output("Taskkill /PID %d /F" % child_pid)
worked for any process for me without permision error
See WindowsError: [Error 5] Access is denied
Answered By - Lesiak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.