How to delete an .exe file written in Python from within the .exe file?

Question:

I am trying to create a script which clones a github repository into the current directory and then deletes the script which called it.

The script is written in Python 3.7.4 and is compiled into an .exe.
I’ve tried using os.remove(sys.argv[0]) which works before compiling but will not work for my end application.
I have also tried several other deletion methods however none of them worked at all, either with or without compiling into an .exe.

import os

def function:
    # code

def main():
    function()
    os.remove(sys.argv[0])

I’m looking to have the .exe delete itself after running like the .py file does however I don’t know the actual method to go around doing this.

Asked By: user12256770

||

Answers:

You can write a batch file to delete the Python file after execution but I am not sure if that is a good idea. It is definitely possible though.

C:test.py:

import os
os.startfile(r"C:test.bat")

C:test.bat:

TASKKILL /IM "process name" 
DEL "C:test.py"
Answered By: Saswath Mishra
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.