gpt4 book ai didi

python - 在 Python 中查看是否有来自管道的输入?

转载 作者:太空狗 更新时间:2023-10-29 20:51:32 25 4
gpt4 key购买 nike

(我想)我知道如何从管道读取数据。我的意思是像这样调用 bash

echo Bähm | ./script.py

这个 Python3 脚本可以解决这个问题。

#!/usr/bin/env python3
import sys

x = sys.stdin.read()

if x:
print(x)
else:
print('no pipe')

sys.exit()

但是当我只是在 bash 上执行此操作时

./script.py

没有任何反应,因为它在等待输入。

所以我想检查(在启动脚本时)是否有来自管道的输入。但我不知道为什么 sizelensys.stdinsys.stdin.buffer .

也许 Python 的第 2 版和第 3 版在处理该问题时也存在差异?

最佳答案

替代@Cyrbil's answer如果你真的需要知道输入是否通过管道输入,你可以使用 isatty :

from sys import stdin
from os import isatty

is_pipe = not isatty(stdin.fileno())

关于python - 在 Python 中查看是否有来自管道的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33871836/

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