[Solved] Python TypeError: iteration over non-sequence on simple list

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?

Solution #1:

os.system() returns the exit code of the process, not the result of the grep commands. This is always an integer. In the meantime, the output of the process itself is not redirected, so it writes to stdout directly (bypassing Python).

You cannot iterate over over an integer.

You should use the subprocess.check_output() function instead if you wanted to retrieve the stdout output of the command.

In this case, you’d be better off using os.listdir() and code the whole search in Python instead:

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

I’ve interpreted the grep -vw jboss- command as filtering out filenames that start with jboss; adjust as needed.

Respondent: Martijn Pieters

Solution #2:

The problem is, that os.system returns the exit code. If you want to capture the output, you can use subprocess.Popen:

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

Also note that the use of the subprocess module is encouraged:

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.

If you do not have to resort to the shell, a pure python solution, as @Martijn Pieters suggests, seems preferable.

Respondent: miku

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published. Required fields are marked *

New ride at Perth's Adventure World a ‘swing on steroids’ - Australasian Leisure Management npp pharma the truth about anabolic steroid drugs and professional sports