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

2016-06-30  本文已影响31人  崩芭大酱

在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)
上一篇下一篇

猜你喜欢

热点阅读