如何在bash中使python脚本“可管道化”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4429966/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:41:44  来源:igfitidea点击:

How to make a python script "pipeable" in bash?

pythonpipe

提问by gbr

I wrote a script and I want it to be pipeablein bash. Something like:

我写了一个脚本,我希望它可以在 bash 中进行管道传输。就像是:

echo "1stArg" | myscript.py

Is it possible? How?

是否可以?如何?

采纳答案by khachik

See this simple echo.py:

看到这个简单echo.py

import sys

if __name__ == "__main__":
    for line in sys.stdin:
        sys.stderr.write("DEBUG: got line: " + line)
        sys.stdout.write(line)

running:

跑步:

ls | python echo.py 2>debug_output.txt | sort

output:

输出:

echo.py
test.py
test.sh

debug_output.txt content:

debug_output.txt 内容:

DEBUG: got line: echo.py
DEBUG: got line: test.py
DEBUG: got line: test.sh

回答by x13n

Everything that reads from stdin is "pipeable". Pipe simply redirects stdout of former program to the latter.

从 stdin 读取的所有内容都是“可管道化的”。管道只是将前一个程序的标准输出重定向到后者。

回答by NPE

In your Python script you simply read from stdin.

在您的 Python 脚本中,您只需stdin.

回答by tokland

I'll complement the other answers with a grepexample that uses fileinputto implement the typical behavior of UNIX tools: 1) if no file is specifie, it reads data from stdin; 2) many files can be sent as arguments; 3) -means stdin.

我将用一个grep示例来补充其他答案,该示例使用fileinput来实现 UNIX 工具的典型行为:1) 如果没有指定文件,则它从 stdin 读取数据;2) 许多文件可以作为参数发送;3)-表示标准输入。

import fileinput
import re
import sys

def grep(lines, regexp):
    return (line for line in lines if regexp.search(line))

def main(args):
    if len(args) < 1:
        print("Usage: grep.py PATTERN [FILE...]", file=sys.stderr)
        return 2 
    regexp = re.compile(args[0])
    input_lines = fileinput.input(args[1:])
    for output_line in grep(input_lines, regexp):
        sys.stdout.write(output_line)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Example:

例子:

$ seq 1 20 | python grep.py "4"
4
14