如何识别脚本是否正在 tty 上运行? [英] How to recognize whether a script is running on a tty?

查看:40
本文介绍了如何识别脚本是否正在 tty 上运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的脚本在交互式 shell 会话中和使用重定向的标准输出运行时(例如,当通过管道传输到某些其他命令时)以不同的方式运行.

I would like my script to act differently in an interactive shell session and when running with redirected stdout (for example when piped to some other command).

如何识别 Python 脚本中发生了这两种情况中的哪一种?

How do I recognize which of these two happen in a Python script?

现有程序中此类行为的示例:grep --color=auto 在交互式 shell 中运行时突出显示匹配项,但在通过管道传输到其他程序时不突出显示.

Example of such behavior in existing program: grep --color=auto highlights matches when running in interactive shell, but doesn't when piped to something else.

推荐答案

import os, sys
os.isatty(sys.stdout.fileno())

sys.stdout.isatty()

这篇关于如何识别脚本是否正在 tty 上运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆