我想通过管道输出ps -ef
逐行转换为 python。
我正在使用的脚本是这个(first.py)-
#! /usr/bin/python
import sys
for line in sys.argv:
print line
不幸的是,“行”被分成由空格分隔的单词。所以,举例来说,如果我这样做
echo "days go by and still" | xargs first.py
我得到的输出是
./first.py
days
go
by
and
still
如何编写脚本以使输出为
./first.py
days go by and still
?
我建议不要使用命令行参数来读取标准输入 (stdin
)。 Python 有一个简单的习惯用法来迭代以下位置的行:stdin
:
import sys
for line in sys.stdin:
sys.stdout.write(line)
我的使用示例(上面的代码保存到iterate-stdin.py
):
$ echo -e "first line\nsecond line" | python iterate-stdin.py
first line
second line
以你的例子:
$ echo "days go by and still" | python iterate-stdin.py
days go by and still
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)