Is there a way to read data that is coming into the command-line, straight into another Python script for execution?
Asked
Active
Viewed 2,526 times
0
-
1Do you mean raw_input() ? – G4bri3l Jun 17 '15 at 18:55
-
I think he means piping output of a command straight to a python script. – ronakg Jun 17 '15 at 18:56
-
1http://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python – Shaun Jun 17 '15 at 18:59
-
Is [this](http://stackoverflow.com/q/30899926/1157100) another attempt at the same question? – 200_success Jun 17 '15 at 19:24
3 Answers
4
You need to read stdin
from the python script.
import sys
data = sys.stdin.read()
print 'Data from stdin -', data
Sample run -
$ date | python test.py
Data from stdin - Wed Jun 17 11:59:43 PDT 2015

ronakg
- 4,038
- 21
- 46
0
Here is an example for future reference and also help others.
Tested with Python 2.6, 2.7, 3.6
# coding=utf-8
"""
Read output from command line passed through a linux pipe
$ vmstat 1 | python read_cmd_output.py 10 3 10
This will warn when the column value breached the threshold for N time consecutively
"""
import sys
import re
def main():
""" Main """
values = []
try:
column, occurrence, threshold = sys.argv[1:]
column = int(column)
occurrence = int(occurrence)
threshold = int(threshold)
except ValueError:
print('Usage: {0} <column> <occurrence> <threshold>'.format(sys.argv[0]))
sys.exit(1)
with sys.stdin:
for line in iter(sys.stdin.readline, b''):
line = line.strip()
if re.match(r'\d', line):
elems = re.split(r'\s+', line)
values.append(elems[column-1])
len(values) > occurrence and values.pop(0)
nb_greater = len([x for x in values if int(x) > threshold])
print(values, nb_greater, 'Warn' if nb_greater >= len(values) else '')
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("\nUser interrupted the script")
sys.exit(1)

Franck
- 71
- 1
- 2