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

无人久伴 提交于 2019-11-30 13:17:24

问题


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


回答1:


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.




回答2:


This way makes your program non OS dependant.

from os import remove
from sys import argv

remove(argv[0])

Bonus points: When parsing arguments the very first argument that you get in sys.argv is equals to "path-to-filename/filename.py"




回答3:


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.




回答4:


There is a rather simple method:

import os   

os.remove("insert the file's path")

If you're facing problems, place an 'r' before the starting quotations mark.




回答5:


Yes, you could use the following:

import os
import sys
import subprocess

# execute and remove after run
(Your python code)
# end of file

dir = os.getcwd()
os.remove(dir+'\%s' % sys.argv[0])

This script can be modified of course, but besides that this should work



来源:https://stackoverflow.com/questions/10112601/how-to-make-scripts-auto-delete-at-the-end-of-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!