使用通配符从子进程调用rm不会删除文件

发布于 2021-01-29 17:16:54

我正在尝试构建一个函数,该函数将从项目的根目录中删除所有以“ 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)

我没有运气-它似乎没有做任何事情。您有什么想法我可能做错了吗?谢谢!

关注者
0
被浏览
39
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    问题在于您要将两个参数传递给subprocess.Popenrm和一个路径,例如/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)
    

    (否则,参数列表将提供给新的shell,而不是命令

    另一种解决方案,更安全和更有效的是使用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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看