0
import os

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

For some reason this gives the TypeError: iteration over non-sequence error on this.

When I do a print test without the for loop, it gives a list of the jboss instances, plus a "0" at the bottom.. The heck?

4

2 回答 2

6

os.system()返回进程的退出代码,而不是命令的结果grep。这始终是一个整数。同时,进程本身的输出没有被重定向,所以它直接写入stdout(绕过 Python)。

您不能迭代整数。

如果您想检索命令的标准输出输出,您应该使用该subprocess.check_output()函数。

在这种情况下,您最好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根据需要进行调整。

于 2013-10-03T20:12:19.837 回答
1

问题是,它os.system返回退出代码。如果要捕获输出,可以使用subprocess.Popen

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

另请注意,subprocess鼓励使用该模块:

subprocess 模块提供了更强大的工具来生成新进程并检索它们的结果;使用该模块优于使用此 [ os.system] 函数。

如果您不必求助于外壳,那么@Martijn Pieters建议的纯 python 解决方案似乎更可取。

于 2013-10-03T20:13:31.517 回答