使用通配符从子进程调用rm不会删除文件
我正在尝试构建一个函数,该函数将从项目的根目录中删除所有以“ prepend”开头的文件。这是我到目前为止的
def cleanup(prepend):
prepend = str(prepend)
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
end = "%s*" % prepend
cmd = 'rm'
args = "%s/%s" % (PROJECT_ROOT, end)
print "full cmd = %s %s" %(cmd, args)
try:
p = Popen([cmd, args], stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True).communicate()[0]
print "p", p
except Exception as e:
print str(e)
我没有运气-它似乎没有做任何事情。您有什么想法我可能做错了吗?谢谢!
-
问题在于您要将两个参数传递给
subprocess.Popen
:rm
和一个路径,例如/home/user/t*
(如果prefix为t
)。Popen
然后将尝试删除以
这种方式 命名的文件:t末尾加星号。如果要
Popen
与通配符一起使用,则应将shell
参数传递为True
。但是,在这种情况下,命令应该是字符串,而不是参数列表:Popen("%s %s" % (cmd, args), shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
另一种解决方案,更安全和更有效的是使用的
glob
模块:import glob files = glob.glob(prepend+"*") args = [cmd] + files Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
总而言之,我同意levon解决方案是更明智的选择。在这种情况下,
glob
答案也是:files = glob.glob(prepend+"*") for file in files: os.remove(file)