代码之家  ›  专栏  ›  技术社区  ›  Jemson

Python子进程脚本失败

  •  0
  • Jemson  · 技术社区  · 8 年前

    已编写以下脚本来删除文件夹中与“保留”期间的日期不匹配的文件。删除除部分匹配此名称的文件外的所有文件。

    /bin/rm /home/backups/!(*"20170920"*|*"20170919"*|*"20170918"*|*"20170917"*|*"20170916"*|*"20170915"*|*"20170914"*)
    
    #!/usr/bin/env python
    from datetime import datetime
    from datetime import timedelta
    import subprocess
    
    ### Editable Variables
    keepdays=7
    location="/home/backups"
    
    count=0
    date_string=''
    for count in range(0,keepdays):
        if(date_string!=""):
            date_string+="|"
        keepdate = (datetime.now() - timedelta(days=count)).strftime("%Y%m%d")
        date_string+="*\""+keepdate+"\"*"
    
    full_cmd="/bin/rm "+location+"/!("+date_string+")"
    subprocess.call([full_cmd], shell=True)
    

    这是脚本返回的结果:

    #./test.py
    
    /bin/rm /home/backups/!(*"20170920"*|*"20170919"*|*"20170918"*|*"20170917"*|*"20170916"*|*"20170915"*|*"20170914"*)
    /bin/sh: 1: Syntax error: "(" unexpected
    

    Python版本是Python 2.7.12

    1 回复  |  直到 8 年前
        1
  •  0
  •   Guillaume    8 年前

    /bin/sh 作为默认的shell,它不支持您想要做的那种globbing。看见 official documentation . 您可以使用 executable 参数到 subprocess.call() /bin/bash /bin/zsh subprocess.call([full_cmd], executable="/bin/bash", shell=True)

    但是Python本身可以更好地为您提供服务,您不需要调用子进程来删除文件:

    #!/usr/bin/env python
    from datetime import datetime
    from datetime import timedelta
    import re
    import os
    import os.path
    
    ### Editable Variables
    keepdays=7
    location="/home/backups"
    
    now = datetime.now()
    keeppatterns = set((now - timedelta(days=count)).strftime("%Y%m%d") for count in range(0, keepdays))
    
    for filename in os.listdir(location):
        dates = set(re.findall(r"\d{8}", filename))
        if not dates or dates.isdisjoint(keeppatterns):
            abs_path = os.path.join(location, filename)
            print("I am about to remove", abs_path)
            # uncomment the line below when you are sure it won't delete any valuable file
            #os.path.delete(abs_path)