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

前端 未结 5 545
臣服心动
臣服心动 2020-12-03 03:15

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

5条回答
  •  鱼传尺愫
    2020-12-03 03:49

    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.

提交回复
热议问题