gpt4 book ai didi

python - 判断 Python 程序是否可以从标准输入读取任何内容的最佳方法是什么?

转载 作者:IT老高 更新时间:2023-10-28 21:53:18 25 4
gpt4 key购买 nike

如果像这样执行,我希望一个程序做一件事:

cat something | my_program.py

如果像这样运行,做另一件事

my_program.py

但是如果我从标准输入读取,那么它会等待用户输入,所以我想在尝试从标准输入读取之前看看是否有任何要读取的内容。

最佳答案

如果您想检测是否有人将数据输入您的程序,或者以交互方式运行它,您可以使用 isatty 来查看 stdin 是否是终端:

$ python -c 'import sys; print sys.stdin.isatty()'
True
$ echo | python -c 'import sys; print sys.stdin.isatty()'
False

关于python - 判断 Python 程序是否可以从标准输入读取任何内容的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/699390/

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