Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe input to python line by line from linux program?

Tags:

python

pipe

I want to pipe the output of ps -ef to python line by line.

The script I am using is this (first.py) -

#! /usr/bin/python

import sys

for line in sys.argv:
   print line

Unfortunately, the "line" is split into words separated by whitespace. So, for example, if I do

echo "days go by and still" | xargs first.py

the output I get is

./first.py
days
go
by
and
still

How to write the script such that the output is

./first.py
days go by and still

?

like image 604
CodeBlue Avatar asked Jul 15 '13 15:07

CodeBlue


People also ask

How does Python get input from the command line?

Python provides developers with built-in functions that can be used to get input directly from users and interact with them using the command line (or shell as it is often called). In Python 2, raw_input() and in Python 3, we use input() function to take input from Command line.

What is piping in Linux?

In Linux, the pipe command lets you sends the output of one command to another. Piping, as the term suggests, can redirect the standard output, input, or error of one process to another for further processing.


2 Answers

Instead of using command line arguments I suggest reading from standard input (stdin). Python has a simple idiom for iterating over lines at stdin:

import sys

for line in sys.stdin:
    sys.stdout.write(line)

My usage example (with above's code saved to iterate-stdin.py):

$ echo -e "first line\nsecond line" | python iterate-stdin.py 
first line
second line

With your example:

$ echo "days go by and still" | python iterate-stdin.py
days go by and still
like image 118
Dr. Jan-Philip Gehrcke Avatar answered Oct 05 '22 22:10

Dr. Jan-Philip Gehrcke


What you want is popen, which makes it possible to directly read the output of a command like you would read a file:

import os
with os.popen('ps -ef') as pse:
    for line in pse:
        print line
        # presumably parse line now

Note that, if you want more complex parsing, you'll have to dig into the documentation of subprocess.Popen.

like image 31
Vincent Fourmond Avatar answered Oct 05 '22 22:10

Vincent Fourmond