I’m trying to build a function that will remove all the files that start with ‘prepend’ from the root of my project. Here’s what I have so far
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)
I’m not having any luck — it doesn’t seem to be doing anything. Do you have any ideas what I might be doing wrong? Thank you!
The problem is that you are passing two arguments to
subprocess.Popen:rmand a path, such as/home/user/t*(if the prefix ist).Popenthen will try to remove a file named exactly this way: t followed by an asterisk at the end.If you want to use
Popenwith the wildcard, you should pass theshellparameter asTrue. In this case, however, the command should be a string, not a list of arguments:(Otherwise, the list of arguments will be given to the new shell, not to the command)
Another solution, safer and more efficient, is to use the
globmodule:However, I agree that Levon’s solution is the saner one. In this case,
globis the answer too: