在Python脚本中检查交互式shell [英] Checking for interactive shell in a Python script

查看:142
本文介绍了在Python脚本中检查交互式shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定调用我的Python脚本的外壳是否处于交互模式.如果处于交互模式,则程序应将输出通过管道传递到less(1)以便于阅读.如果没有,它应该只将其输出打印到stdout,以便将其通过管道传输到打印机,文件或其他寻呼机.

I need to determine whether the shell which invoked my Python script was in interactive mode or not. If it was in interactive mode, the program should pipe output to less(1) for easy reading. If not, it should simply print its output to stdout, to allow it to be piped away to a printer, file, or a different pager.

在shell脚本中,我会检查是否定义了提示变量$ PS1,或者在$-变量中存储的标志中寻找-i选项.

In a shell script, I would have checked if the prompt variable $PS1 was defined, or looked for the -i option among the flags stored in the $- variable.

从Python内部测试交互性的首选方法是什么?

What is the preferred method for testing interactivity from within Python?

推荐答案

这通常效果很好

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

这篇关于在Python脚本中检查交互式shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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