使用通配符从子进程调用rm不会删除文件 [英] Calling rm from subprocess using wildcards does not remove the files
问题描述
我正在尝试构建一个功能,将从我的项目根目录中删除所有以'prepend'开头的文件。这是我到目前为止
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!
推荐答案
问题是你传递两个参数到 subprocess.Popen
: rm
和路径,如 / home / user / t *
(如果前缀为 T
)。 Popen
然后将尝试删除一个名为的文件,这样:t后面加上一个星号。
The problem is that you are passing two arguments to subprocess.Popen
: rm
and a path, such as /home/user/t*
(if prefix is t
). Popen
then will try to remove a file named exactly this way: t followed by an asterisk at the end.
如果要使用通配符 Popen
,则应将 shell
参数作为真
。但是,在这种情况下,命令应该是字符串,而不是参数列表:
If you want to use Popen
with the wildcard, you should pass the shell
parameter as True
. In this case, however, the command should be a string, not a list of arguments:
Popen("%s %s" % (cmd, args), shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
另一个更安全,更高效的解决方案是使用 glob
模块:
Another solution, safer and more efficient, is to use the glob
module:
import glob
files = glob.glob(prepend+"*")
args = [cmd] + files
Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
然而,总而言之,我同意levon解决方案是更为清晰的解决方案。在这种情况下, glob
也是答案:
All in all, however, I agree that levon solution is the saner one. In this case, glob
is the answer too:
files = glob.glob(prepend+"*")
for file in files:
os.remove(file)
这篇关于使用通配符从子进程调用rm不会删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!