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

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

问题描述

我需要确定调用我的 Python 脚本的 shell 是否处于交互模式.如果它处于交互模式,程序应该将输出通过管道传输到less(1) 以便于阅读.如果没有,它应该简单地将其输出打印到标准输出,以允许它通过管道传输到打印机、文件或不同的寻呼机.

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天全站免登陆