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.
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.
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:
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.
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With