python26实例[subst然后删除文件夹]
时间:2011-03-22 来源:iTech
有些时候某些文件夹下的文件路径太长,超出了windows系统的限制,导致此文件夹不能被删除。 此时我们需要先subst此文件夹然后再删除,以下脚本帮你自动完成。
代码:
import osimport sys
import shutil
import subprocess
def runCommand(cmd):
return subprocess.call(cmd)
def substDriveForPath(drive, path):
substcmd = "subst" + " " + drive + " " + path
return runCommand(substcmd)
def unSubstDriveForPath(drive):
unsubstcmd = "subst" + " " +drive + " " + "/d"
runCommand(unsubstcmd)
def autoSubst(path):
result = False
useddrive = ""
for drive in "ZYXWVUTSRQPONMLKJIHGFEDCBA":
fulldrive = drive + ":"
returncode = substDriveForPath(fulldrive,path)
if(returncode == 0):
useddrive = fulldrive
break
if(not useddrive == ""):
result = True
return result, useddrive
def rmDirwithSubst(dir, subst = True):
if not os.path.exists(dir) and not os.path.isdir(dir) :
print 'path %s is not existed or is not a directory' %dir
return False
if subst:
parent, curdir = os.path.split(dir)
re, d = autoSubst(parent)
if re == False :
print 'subst failed'
return False
dir = d + '\\' + curdir
shutil.rmtree(dir)
unSubstDriveForPath(d)
return True
def usage():
usage = '\
When the dirctory cannot be removed in which some files path are too long.\n\
Usage: python %s folder1 [folder2 ...]\n' %sys.argv[0]
print usage
if __name__ == '__main__':
if len(sys.argv) < 2 : usage()
for folder in sys.argv[1:]:
rmDirwithSubst(folder)
完!
相关阅读 更多 +