Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Nice way to iterate over shell command result

is there a "nice" way to iterate over the output of a shell command?

I'm looking for the python equivalent for something like:

ls | while read file; do
    echo $file
done

Note that 'ls' is only an example for a shell command which will return it's result in multiple lines and of cause 'echo' is just: do something with it.

I known of these alternatives: Calling an external command in Python but I don't know which one to use or if there is a "nicer" solution to this. (In fact "nicer" is the main focus of this question.)

This is for replacing some bash scripts with python.

like image 871
Scheintod Avatar asked Dec 05 '13 00:12

Scheintod


People also ask

How do you iterate through a list in Python while loop?

Iterate Through List in Python Using While Loop The second method to iterate through the list in python is using the while loop. In while loop way of iterating the list, we will follow a similar approach as we observed in our first way, i.e., for-loop method. We have to just find the length of the list as an extra step.

How to echo a shell command in Python?

The first thing we do in our Python file is import the os module, which contains the system function that can execute shell commands. The next line does exactly that, runs the echo command in our shell through Python. In your Terminal, run this file with using the following command, and you should see the corresponding output:

How do I execute a shell command in Python?

The os.system () function executes a command, prints any output of the command to the console, and returns the exit code of the command. If we would like more fine grained control of a shell command's input and output in Python, we should use the subprocess module. The subprocess module is Python's recommended way to executing shell commands.

What types can you iterate over in Python?

But these are by no means the only types that you can iterate over. Many objects that are built into Python or defined in modules are designed to be iterable. For example, open files in Python are iterable. As you will see soon in the tutorial on file I/O, iterating over an open file object reads data from the file.


Video Answer


1 Answers

you can open a pipe ( see doc ):

import os

with os.popen('ls') as pipe:
    for line in pipe:
        print (line.strip())

as in the document this syntax is depreciated and is replaced with more complicated subprocess.Popen

from subprocess import Popen, PIPE
pipe = Popen('ls', shell=True, stdout=PIPE)

for line in pipe.stdout:
    print(line.strip())
like image 74
behzad.nouri Avatar answered Oct 16 '22 11:10

behzad.nouri