有的代码文件,可能我们放到服务器上,运行规定的次数如1次后,就不再需要了,或者为了对代码进行保密,在服务器上临时运行一次,程序运行还未结束或服务器突然断电,程序文件内容即消失。
有两种方式,可以在执行程序开始,随着代码载入内存开始,对该代码文件实行文件销毁,或者对代码文件里内容进行销毁。
大家可以试试下面的代码,嘿嘿~~
print "code start" def self_delete(max_times): import os file_name = os.path.split(__file__)[1] times = 0 try: with open('times', 'r') as fp: times = int(fp.readlines()[0]) except: pass if times < max_times-1: times += 1 try: with open('times', 'w') as fp: fp.writelines(str(times)) except: pass else: try: os.remove('times') except: pass print "delete codes!!!" ## delete file!!! # os.remove(file_name) ## delete codes!!! with open(file_name, 'r') as fp: codes = fp.readlines() with open(file_name, 'w') as fp: fp.writelines(codes[:1]+codes[-1:]) self_delete(1) # set your codes running times #TODO ''' add your codes here ''' print 'add your codes here' import time for i in range(10): print 'hello world' time.sleep(i) print "code end"
转载请注明:宁哥的小站 » 一段用于保密的自动销毁代码