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

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


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 sysfor 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 linesecond line

With your example:

$ echo "days go by and still" | python iterate-stdin.pydays go by and still


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

import oswith 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.


I know this is really out-of-date, but you could try

#! /usr/bin/pythonimport sysprint(sys.argv, len(sys.argv))if len(sys.argv) == 1:    message = input()else:    message = sys.argv[1:len(sys.argv)]print('Message:', message)

and I tested it thus:

$ ./test.py['./test.py'] 1this is a testMessage: this is a test$ ./test.py this is a test['./test.py', 'this', 'is', 'a', 'test'] 5Message: ['this', 'is', 'a', 'test']$ ./test.py "this is a test"['./test.py', 'this is a test'] 2Message: ['this is a test']$ ./test.py 'this is a test'['./test.py', 'this is a test'] 2Message: ['this is a test']$ echo "This is a test" | ./test.py['./test.py'] 1Message: This is a test

Or, if you wanted the message to be one string, each and every time, then

    message = ' '.join(sys.argv[1:len(sys.argv)])

would do the trick on line 8