如何从Linux程序逐行将输入管道传输到python? [英] How to pipe input to python line by line from linux program?
本文介绍了如何从Linux程序逐行将输入管道传输到python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想逐行将ps -ef
的输出通过管道传递到python.
I want to pipe the output of ps -ef
to python line by line.
我正在使用的脚本是这个(first.py)-
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
我得到的输出是
./first.py
days
go
by
and
still
如何编写脚本以使输出为
How to write the script such that the output is
./first.py
days go by and still
?
推荐答案
我不太明白为什么要使用命令行参数而不是简单地从标准输入中读取. Python有一个简单的习惯用法,可以在stdin上遍历行:
I do not quite understand why you want to use commandline arguments instead of simply reading from standard input. Python has a simple idiom for iterating over lines at stdin:
import sys
for line in sys.stdin:
sys.stdout.write(line)
我的用法示例:
$ echo -e "first line\nsecond line" | python python_iterate_stdin.py
first line
second line
您的用法示例:
$ echo "days go by and still" | python python_iterate_stdin.py
days go by and still
这篇关于如何从Linux程序逐行将输入管道传输到python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文