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

前端 未结 5 524
臣服心动
臣服心动 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 04:02

    Neomind's answer seems to do the trick. But if deleting the file while it's in memory bothers you, and you're looking for a pure python solution, then you could use subprocess to create a new process with the explicit purpose of deleting your original script file. Something like this should work:

    import sys, subprocess 
    subprocess.Popen("python -c \"import os, time; time.sleep(1); os.remove('{}');\"".format(sys.argv[0]))
    sys.exit(0)
    

    You probably wouldn't need the timeout in there but I've added it just to make sure that the process from the original script has been given enough time to close itself.

提交回复
热议问题