gpt4 book ai didi

python - Chainable python shell脚本,可以多次使用

转载 作者:行者123 更新时间:2023-11-28 21:53:03 25 4
gpt4 key购买 nike

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

$ myscript.py |脚本.py |我的脚本.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"

最佳答案

您试图在标准输入上查找文件的大小,但标准输入不是文件,因此失败。

相反,只需阅读并看看您是否有所收获:

#!/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 语义:

  1. 您说您希望第二个示例打印NO OUTPUT 然后GOT INPUT >>> NO OUTPUT。这是不正常的:echo foo |荷兰 | rev 不会打印 1 foo 后跟 oof 1

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

    echo foo |荷兰 |发球台/dev/stderr |转

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

    该程序打印一条关于如何执行此操作的信息性消息。如果您强烈认为 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

关于python - Chainable python shell脚本,可以多次使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27284393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com