在linux下判断当前的环境是不是在终端下运行的

在linux下判断当前的环境是不是在终端下运行的

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import re
import sys


def is_terminal(path=None):
    """Is true if the terminal is a real one
    Like the linux terminal console

    >>> is_terminal("/dev/tty0")
    True

    >>> is_terminal("/dev/ttyUSB0")
    False

    >>> is_terminal("/dev/ttyS0")
    False

    >>> is_terminal("/dev/tty")
    True

    >>> is_terminal("/dev/console")
    True
    """
    is_terminal = False
    try:
        ttyname = path or os.ttyname(sys.stdin.fileno())
        print(ttyname)
        is_tty = re.match("/dev/tty([0-9]|$)", ttyname) is not None
        is_console = ttyname == "/dev/console"
        is_terminal = is_tty or is_console
    except OSError:
        pass
    return is_terminal

if __name__ == "__main__":
    result = is_terminal()
    print(result)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容