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

我想创建一个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

这是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"

python大神给出的解决方案

您试图在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")

该程序没有执行您想要的操作,而是使用标准的UNIX语义:

您说您要第二个示例先打印NO OUTPUT,然后再打印GOT INPUT >>> NO OUTPUT。这是不正常的:echo foo | nl | rev将不打印1 foo,然后再打印oof 1

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

echo foo | nl | tee /dev/stderr | rev
当由用户直接运行时,程序应从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