Search code examples
pythonwindowsself-destruction

How to make scripts auto-delete at the end of execution?


Is it possible to make a python script that will delete the .py file at the end of its execution (self-delete) in windows?


Solution

  • I'm not sure deleting a file while it's in memory would be a good idea. Try running a batch file from the script which closes the script process, then deletes the script file.

    There may be a native method to self destruct a script, but I am not aware of it.

    EDIT: Here is a simple example of how you could accomplish this using the method I described:

    In the script

    # C:\test.py
    import os
    os.startfile(r"C:\sampleBatch.bat")
    

    In the batch

    # C:\sampleBatch.bat
    TASKKILL /IM "process name" #For me, this was "ipy64.exe" because I use IronPython.
    DEL "C:\test.py"
    

    You may not even need to kill the process to delete the file, but it is safer to do so. Hope this helps.