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

前端 未结 3 1338
故里飘歌
故里飘歌 2020-11-30 22:21

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         


        
相关标签:
3条回答
  • 2020-11-30 22:56

    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.

    0 讨论(0)
  • 2020-11-30 23:12

    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
    
    0 讨论(0)
  • 2020-11-30 23:14

    Another approach is to use the input() function (the code is for Python 3).

    while True:
            try:
                line = input()
                print('The line is:"%s"' % line)
            except EOFError:
                # no more information
                break
    

    The difference between the answer and the answer got by Dr. Jan-Philip Gehrcke is that now each of the lines is without a newline (\n) at the end.

    0 讨论(0)
提交回复
热议问题