'How can I delete the application after it upon closing it?
How to delete python executable file after it finishes? I have tried the following:
os.remove()- deleting the python exe fileos.chmod()- removing the readOnlyos.getcwd- combined withos.remove()shutile.rmtree- combined withos.getcwd()sys.argv[0]
All of these works when I still use .py extension, but when I convert it to exe it gives me permission error. How do I remove it?
I want to delete the main.exe because I'm going to distribute it to my friends. I don't want the program to stay inside their system permanently that's why I decided to create an auto-delete script.
The code I'm running revolves under pyqt5.
Solution 1:[1]
you can achieve this by creating a separate bat file, and calling that after executing your code
if __name__ == "__main__":
main()
cleanup()
here is the cleanup function
import os
import sys
def cleanup():
with open("cleanup.bat", "w+") as file:
file.write(f"DEL /F \"{sys.argv[0]}\" \nDEL /F \"{os.getcwd()}\\cleanup.bat\"")
os.startfile(os.getcwd()+"\\cleanup.bat")
Solution 2:[2]
- I would start with ensuring that what you are trying to do is what you actually need. If you provide more details about your real purpose, probably we could find a better solution without using strange workarounds and/or crutches to solve your problem
- In Windows 10 it is not possible to remove an executable when it is running (no matter whether you are trying to remove the file from the inside or the outside of the executable), this is why you are getting permission error with the .exe file. Probably there is some workaround which would use some special Windows-only features (because as far as I'm concerned it's not possible to do what you are asking about with libraries such as
threading/multiprocessing), but if you really want to do this, the easiest way I see is using another executable intended specifically to delete the executable which calls it after the original executable finishes.
But, again, this is not a good solution and to be honest, I don't think there is a perfect one, because your goal seems an anti-pattern to me
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ddjerqq |
| Solution 2 | Kolay.Ne |
