如何从linux程序一行一行地将输入管道输入到python?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17658512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pipe input to python line by line from linux program?
提问by CodeBlue
I want to pipe the output of ps -ef
to python line by line.
我想ps -ef
逐行将输出通过管道传输到 python。
The script I am using is this (first.py) -
我正在使用的脚本是这个 (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
?
?
采纳答案by Dr. Jan-Philip Gehrcke
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:
我不太明白为什么要使用命令行参数而不是简单地从标准输入中读取。Python 有一个简单的习惯用法,用于在 stdin 上迭代行:
import sys
for line in sys.stdin:
sys.stdout.write(line)
My usage example:
我的用法示例:
$ echo -e "first line\nsecond line" | python python_iterate_stdin.py
first line
second line
Your usage example:
您的使用示例:
$ echo "days go by and still" | python python_iterate_stdin.py
days go by and still
回答by Vincent Fourmond
What you want is popen
, which makes it possible to directly read the output of a command like you would read a file:
您想要的是popen
,这使得可以像读取文件一样直接读取命令的输出:
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
.
请注意,如果您想要更复杂的解析,则必须深入研究subprocess.Popen
.