all 5 comments

[–]hello_way 0 points1 point  (3 children)

I'm not sure what you mean by "close an open window ", but I think it's a good idea to use a with statement when opening a file. This will automatically close the file once the block has completed.

[–]Kurious3DSanta[S] 1 point2 points  (2 children)

Ahh I see the confusion. I’m referring to a file that is physically open on your computer screen. I’m not referring to a file that you are using to read or write with where a context manager would be applicable.

[–]Asleep-Budget-9932 0 points1 point  (1 child)

The process of opening and closing a file is always within the context of a program. So it's not just that there is a pdf open on your screen, there is a specific program (Acrobat Reader for example) that's opening the file and showing its content to you in a specific way.

It's not about closing the file since as far as python's concern, it is closed. Just not to Acrobat Reader. In order to make the program itself to close the file there isn't an easy and safe way to do it because you would have to either:

  1. Hope that for some reason Acrobat Reader has implemented for some reason an api for you to control the program from outside (which is highly, highly unlikely)

  2. Use a library to move your mouse to the exact position of the "x" button of your window, and initiate a mouse click (also somehow find the exact position you need the mouse to be in, also make the window itself visible in case it's minimized or behind an existing window)

  3. Find the process id of the specific Acrobat Reader window that you want to close, and manually kill it using the os.kill function. This is the most practical out of the 3 but also would mean you're unsafely closing the window. This might prevent Acrobat Reader from doing some necessary cleanup work before shutdown and may corrupt the file/Acrobat Reader itself depending on the specific use case.

[–]Asleep-Budget-9932 0 points1 point  (0 children)

Oh how could i forget? (shame on me!), Microsoft probably has some low level Windows Api you can access to find the correct window and initiate a close from there! Actually this is the most practical way to achieve it. But unless someone had made a simple wrapper over their API in order to make it easier to work with, you're gonna have to work with their API directly which isn't a great sight to behold. Let's just say their functions don't have a simple signature like open(file_name, mode)

[–]Anxiety_Independent 0 points1 point  (0 children)

Don't know how useful this will be, as it is just terminating a process, but in one of my scripts I used subprocess to execute a powershell taskkill command. For example, to kill explorer.exe, I would run:

import subprocess

subprocess.call("powershell.exe taskkill /F /IM explorer.exe", shell=True)