2016-04-21 61 views
0

我正在尝试使用subprocess.call调用列表时间。它似乎没有工作。任何更好的方式来做到这一点。调用子进程中的列表项

import os, sys 
import subprocess as sb 


files_to_remove=['*.jpg','*.txt','*.gif'] 

for item in files_to_remove: 
    try: 
     **sb.call(['rm' %s]) %item** # not working 

    except: 
     print 'no %s files in directory' %item 
+0

子进程调用中双星的用途是什么? –

+0

如果你没有空白,那么问题会更加明显,你也不需要一个子进程来做到这一点 –

+0

建议你看看[这个问题和答案](http:// stackoverflow。 COM /问题/ 6703668 /删除-肯定的 - 文件 - 使用的Python)。 – mshildt

回答

0

没有必要在这里使用一个子

import glob 
import os 

files_to_remove = ['*.jpg', '*.txt', '*.gif'] 
for files_glob in files_to_remove: 
    for filename in glob.glob(files_glob): 
     os.remove(filename) 

如果我们使用一个子坚持(我们不会为删除这些文件)我们会做

import glob 
import subprocess 

files_to_remove=['*.jpg', '*.txt', '*.gif'] 

for files_glob in files_to_remove: 
    matches = glob.glob(files_glob) 
    if matches: 
     subprocess.check_call(['rm'] + matches) 
    else: 
     print 'no %s files in directory' % files_glob 

最好不要使用shell=True

+0

谢谢。你的第一个方法很棒。说如果我有一个目录(不是文件)。我如何在这种情况下使用glob?在子进程中,我可以这样做,rm -r

kirit

+1

你会输入shutil,然后输入shutil.rmtree(“/ path/to/the/dir”)。 Globbing不适用 - glob是shell中'*'语法的名称,但在这种情况下,我们没有带'*'的路径。 –

0

它没有按预期工作,因为它逃避了争论。而下面的工作:

#!/usr/bin/python 

import os, sys 
import subprocess as sb 

files_to_remove=['*.jpg','*.txt','*.gif'] 

for item in files_to_remove: 
    try: 
     sb.check_call(['rm ' + item], shell=True) 
    except sb.CalledProcessError as e: 
     print(e.output) 
    except: 
     print("unknown error") 
+0

谢谢。它的工作现在好了 – kirit