2016-04-21 57 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