可链接的python shell脚本,可以多次使用

Ria*_*zvi 2 python unix bash shell

我想创建一个python shell脚本myscript.py,它可以多次将输出提供给管道或接收管道输入.例如.

$ myscript.py | myscript.py | myscript.py ...

以下实施仅在有限的范围内起作用:

$ myscript.py
NO INPUT
(ok)

$ echo 'hello' | myscript.py
GOT INPUT >>> hello
(ok)


$ myscript.py | myscript.py
NO INPUT

(not ok, should be)
NO INPUT
GOT INPUT >>> NO INPUT
Run Code Online (Sandbox Code Playgroud)

这是myscript.py的内容:

#!/usr/bin/env python

if __name__=="__main__":
    import sys,os
    if (os.fstat(sys.stdin.fileno()).st_size > 0):
        stdincontents=sys.stdin.read()
        print "GOT INPUT >>> " + stdincontents
    else:
        print "NO INPUT"
Run Code Online (Sandbox Code Playgroud)

tha*_*guy 5

你试图在stdin上找到文件的大小,但是stdin不是一个文件,所以它失败了.

相反,只需阅读并看看你是否得到了一些东西:

#!/usr/bin/env python
from __future__ import print_function

if __name__=="__main__":
    import sys,os
    if (os.isatty(0)):
        print("This program reads from stdin, which is currently a terminal.\n" +
              "Please type some text and finish with Ctrl+D.\n" +
              "(This informative text is not passed on.)", file=sys.stderr);

    stdincontents=sys.stdin.read()
    if(len(stdincontents) > 0):
        print("GOT INPUT >>> " + stdincontents)
    else:
        print("NO INPUT")
Run Code Online (Sandbox Code Playgroud)

该程序使用标准的UNIX语义,而不是按照您的意愿执行操作:

  1. 你说你想要你的第二个例子打印NO OUTPUT然后GOT INPUT >>> NO OUTPUT.这不正常:echo foo | nl | rev不打印1 foo后跟oof 1.

    如果要查看管道中任意点的输出以及最终输出,请使用

    echo foo | nl | tee /dev/stderr | rev

  2. 当用户直接运行时,程序应该从stdin读取,而不是在没有输入的情况下放弃和运行.

    该程序打印有关如何执行此操作的信息性消息.如果您强烈认为Unix是错误的,您可以将其切换为不读取输入.

以下是它的工作原理:

$ echo hello | ./myscript.py
GOT INPUT >>> hello

$ echo hello | ./myscript.py | ./myscript.py
GOT INPUT >>> GOT INPUT >>> hello

$ ./myscript.py | ./myscript.py 
This program reads from stdin, which is currently a terminal.
Please type some text and finish with Ctrl+D
(This informative text is not passed on.)
***pressed ctrl+d here***
GOT INPUT >>> NO INPUT
Run Code Online (Sandbox Code Playgroud)