Python子进程脚本失败

时间:2017-09-20 11:33:28

标签: python shell subprocess rm

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

该命令在shell中运行,但在子进程调用时失败。

/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 个答案:

答案 0 :(得分:0)

正如@hjpotter所说,子进程将使用/bin/sh作为默认shell,它不支持你想要做的那种通配符。见official documentation。您可以使用executable参数将其更改为subprocess.call(),并使用更合适的shell(例如/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)