2013-10-03 29 views
0
import os 

test = os.system("ls /etc/init.d/ | grep jboss- | grep -vw jboss-") 
for row in test: 
    print row 

由於某些原因,這給出了TypeError:對此的非序列錯誤的迭代。Python TypeError:通過簡單列表上的非序列進行迭代

當我做一個沒有for循環的打印測試時,它給出了一個jboss實例的列表,在底部加上一個「0」..赫克?

+4

閱讀[文檔](http://docs.python.org/2/library/os.html#os.system)。 'os.system'不會返回你運行的程序的任何輸出。 – BrenBarn

+0

您將看到管道的標準輸出與「test」(0)的實際值的組合。 – chepner

回答

6

os.system()返回退出代碼的過程的grep命令的結果。這總是一個整數。與此同時,進程本身的輸出不會被重定向,所以它直接寫入stdout(繞過Python)。

你不能遍歷一個整數。

如果您想要檢索命令的標準輸出,則應該使用subprocess.check_output() function

在這種情況下,你會使用os.listdir()和代碼在Python整個搜索,而不是更好:

for filename in os.listdir('/etc/init.d/'): 
    if 'jboss-' in filename and not filename.startswith('jboss-'): 
     print filename 

我已經解釋了grep -vw jboss-命令過濾掉的文件名是jboss開始;根據需要調整。

1

問題是,os.system返回退出代碼。如果你想捕捉的輸出,你可以使用subprocess.Popen

import subprocess 
p = subprocess.Popen("ls", stdout=subprocess.PIPE), 
out, err = p.communicate() 
files = out.split('\n') 

另外要注意的是,使用subprocess模塊的鼓勵:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this [ os.system ] function.

如果你沒有訴諸外殼,一個純粹的Python解決方案,如@Martijn Pieters所暗示的,似乎更可取。