Python os.ctermid() Examples

The following are 12 code examples of os.ctermid(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: main.py    From kitty with GNU General Public License v3.0 6 votes vote down vote up
def main(args: List[str]) -> Optional[Dict[str, Any]]:
    text = ''
    if sys.stdin.isatty():
        if '--help' not in args and '-h' not in args:
            print('You must pass the text to be hinted on STDIN', file=sys.stderr)
            input(_('Press Enter to quit'))
            return None
    else:
        text = sys.stdin.buffer.read().decode('utf-8')
        sys.stdin = open(os.ctermid())
    try:
        opts, items = parse_hints_args(args[1:])
    except SystemExit as e:
        if e.code != 0:
            print(e.args[0], file=sys.stderr)
            input(_('Press Enter to quit'))
        return None
    if items and not (opts.customize_processing or opts.type == 'linenum'):
        print('Extra command line arguments present: {}'.format(' '.join(items)), file=sys.stderr)
        input(_('Press Enter to quit'))
    return run(opts, text, items) 
Example #2
Source File: console.py    From pycraft with GNU General Public License v2.0 6 votes vote down vote up
def _get_terminal_size():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct
            return struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
        except:
            pass

    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)

    if not cr:
        try:
            with open(os.ctermid()) as fd:
                cr = ioctl_GWINSZ(fd)
        except:
            cr = (os.getenv('LINES', 25), os.getenv('COLUMNS', 80))

    return int(cr[1]), int(cr[0]) 
Example #3
Source File: display-terminal-info.py    From FunUtils with MIT License 5 votes vote down vote up
def main():
    fd = sys.stdin.fileno()
    locale.setlocale(locale.LC_ALL, '')
    encoding = locale.getpreferredencoding()

    print('os.isatty({0}) => {1}'.format(fd, os.isatty(fd)))
    print('locale.getpreferredencoding() => {0}'.format(encoding))

    display_conf(kind='pathconf',
                 names=os.pathconf_names,
                 getter=lambda name: os.fpathconf(fd, name))

    try:
        (iflag, oflag, cflag, lflag, ispeed, ospeed, cc
         ) = termios.tcgetattr(fd)
    except termios.error as err:
        print('stdin is not a typewriter: {0}'.format(err))
    else:
        display_bitmask(kind='Input Mode',
                        bitmap=BITMAP_IFLAG,
                        value=iflag)
        display_bitmask(kind='Output Mode',
                        bitmap=BITMAP_OFLAG,
                        value=oflag)
        display_bitmask(kind='Control Mode',
                        bitmap=BITMAP_CFLAG,
                        value=cflag)
        display_bitmask(kind='Local Mode',
                        bitmap=BITMAP_LFLAG,
                        value=lflag)
        display_ctl_chars(index=CTLCHAR_INDEX,
                          cc=cc)
        print('os.ttyname({0}) => {1}'.format(fd, os.ttyname(fd)))
        print('os.ctermid() => {0}'.format(os.ttyname(fd))) 
Example #4
Source File: termrule.py    From termrule with MIT License 5 votes vote down vote up
def _term_size(self):
        """
        Method returns lines and columns according to terminal size
        """
        for fd in (0, 1, 2):
            try:
                return self._ioctl_GWINSZ(fd)
            except:
                pass
        # try os.ctermid()
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            try:
                return self._ioctl_GWINSZ(fd)
            finally:
                os.close(fd)
        except:
            pass
        # try `stty size`
        try:
            return tuple(int(x) for x in os.popen("stty size", "r").read().split())
        except:
            pass
        # try environment variables
        try:
            return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
        except:
            pass
        # i give up. return default.
        return (25, 80) 
Example #5
Source File: common.py    From catkin_tools with Apache License 2.0 5 votes vote down vote up
def terminal_width_linux():
    """Returns the estimated width of the terminal on linux"""
    from fcntl import ioctl
    from termios import TIOCGWINSZ
    import struct
    try:
        with open(os.ctermid(), "rb") as f:
            height, width = struct.unpack("hh", ioctl(f.fileno(), TIOCGWINSZ, "1234"))
    except (IOError, OSError, struct.error):
        # return default size if actual size can't be determined
        __warn_terminal_width_once()
        return __default_terminal_width
    return width 
Example #6
Source File: main.py    From kitty with GNU General Public License v3.0 5 votes vote down vote up
def real_main(args: List[str]) -> None:
    msg = 'Show an error message'
    cli_opts, items = parse_args(args[1:], OPTIONS, '', msg, 'hints', result_class=ErrorCLIOptions)
    error_message = sys.stdin.buffer.read().decode('utf-8')
    sys.stdin = open(os.ctermid())
    print(styled(cli_opts.title, fg_intense=True, fg='red', bold=True))
    print()
    print(error_message)
    print()
    input('Press Enter to close.') 
Example #7
Source File: main.py    From kitty with GNU General Public License v3.0 5 votes vote down vote up
def main(args: List[str]) -> NoReturn:
    cli_opts, items = parse_args(args[1:], OPTIONS, usage, help_text, 'kitty +kitten clipboard', result_class=ClipboardCLIOptions)
    if items:
        raise SystemExit('Unrecognized extra command line arguments')
    data: Optional[bytes] = None
    if not sys.stdin.isatty():
        data = sys.stdin.buffer.read()
        sys.stdin = open(os.ctermid(), 'r')
    loop = Loop()
    handler = Clipboard(data, cli_opts)
    loop.loop(handler)
    if loop.return_code == 0 and handler.clipboard_contents:
        sys.stdout.write(handler.clipboard_contents)
        sys.stdout.flush()
    raise SystemExit(loop.return_code) 
Example #8
Source File: terminal.py    From textfsm with Apache License 2.0 5 votes vote down vote up
def TerminalSize():
  """Returns terminal length and width as a tuple."""
  try:
    with open(os.ctermid()) as tty_instance:
      length_width = struct.unpack(
          'hh', fcntl.ioctl(tty_instance.fileno(), termios.TIOCGWINSZ, '1234'))
  except (IOError, OSError, NameError):
    try:
      length_width = (int(os.environ['LINES']),
                      int(os.environ['COLUMNS']))
    except (ValueError, KeyError):
      length_width = (24, 80)
  return length_width 
Example #9
Source File: display-terminfo.py    From python-scripts with GNU General Public License v3.0 5 votes vote down vote up
def main():
    fd = sys.stdin.fileno()
    locale.setlocale(locale.LC_ALL, '')
    encoding = locale.getpreferredencoding()

    print('os.isatty({0}) => {1}'.format(fd, os.isatty(fd)))
    print('locale.getpreferredencoding() => {0}'.format(encoding))

    display_conf(kind='pathconf',
                 names=os.pathconf_names,
                 getter=lambda name: os.fpathconf(fd, name))

    try:
        (iflag, oflag, cflag, lflag, ispeed, ospeed, cc
         ) = termios.tcgetattr(fd)
    except termios.error as err:
        print('stdin is not a typewriter: {0}'.format(err))
    else:
        display_bitmask(kind='Input Mode',
                        bitmap=BITMAP_IFLAG,
                        value=iflag)
        display_bitmask(kind='Output Mode',
                        bitmap=BITMAP_OFLAG,
                        value=oflag)
        display_bitmask(kind='Control Mode',
                        bitmap=BITMAP_CFLAG,
                        value=cflag)
        display_bitmask(kind='Local Mode',
                        bitmap=BITMAP_LFLAG,
                        value=lflag)
        display_ctl_chars(index=CTLCHAR_INDEX,
                          cc=cc)
        print('os.ttyname({0}) => {1}'.format(fd, os.ttyname(fd)))
        print('os.ctermid() => {0}'.format(os.ttyname(fd))) 
Example #10
Source File: pass.py    From enpass-cli with GNU General Public License v3.0 5 votes vote down vote up
def __getTermSize(self):
        """
        returns (lines:int, cols:int)
        """
        import os, struct
        def ioctl_GWINSZ(fd):
            import fcntl, termios
            return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))

        # try stdin, stdout, stderr
        for fd in (0, 1, 2):
            try:
                return ioctl_GWINSZ(fd)
            except:
                pass

        # try os.ctermid()
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            try:
                return ioctl_GWINSZ(fd)
            finally:
                os.close(fd)
        except:
            pass

        # try `stty size`
        try:
            return tuple(int(x) for x in os.popen("stty size", "r").read().split())
        except:
            pass

        # try environment variables
        try:
            return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
        except:
            pass

        # i give up. return default.
        return (25, 80) 
Example #11
Source File: tools.py    From picos with GNU General Public License v3.0 4 votes vote down vote up
def getTerminalSize(self):
        """
        returns (lines:int, cols:int)
        """
        import os
        import struct

        def ioctl_GWINSZ(fd):
            import fcntl
            import termios
            return struct.unpack(
                "hh", fcntl.ioctl(
                    fd, termios.TIOCGWINSZ, "1234"))
        # try stdin, stdout, stderr
        for fd in (0, 1, 2):
            try:
                return ioctl_GWINSZ(fd)
            except:
                pass
        # try os.ctermid()
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            try:
                return ioctl_GWINSZ(fd)
            finally:
                os.close(fd)
        except:
            pass
        # try `stty size`
        try:
            return tuple(
                int(x) for x in os.popen(
                    "stty size",
                    "r").read().split())
        except:
            pass
        # try environment variables
        try:
            return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
        except:
            pass
        # i give up. return default.
        return (25, 80)


# a not writable dict 
Example #12
Source File: terminal.py    From st2 with Apache License 2.0 4 votes vote down vote up
def get_terminal_size_columns(default=DEFAULT_TERMINAL_SIZE_COLUMNS):
    """
    Try to retrieve COLUMNS value of terminal size using various system specific approaches.

    If terminal size can't be retrieved, default value is returned.

    NOTE 1: COLUMNS environment variable is checked first, if the value is not set / available,
            other methods are tried.

    :rtype: ``int``
    :return: columns
    """
    # 1. Try COLUMNS environment variable first like in upstream Python 3 method -
    # https://github.com/python/cpython/blob/master/Lib/shutil.py#L1203
    # This way it's consistent with upstream implementation. In the past, our implementation
    # checked those variables at the end as a fall back.
    try:
        columns = os.environ['COLUMNS']
        return int(columns)
    except (KeyError, ValueError):
        pass

    def ioctl_GWINSZ(fd):
        import fcntl
        import termios
        # Return a tuple (lines, columns)
        return struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))

    # 2. try stdin, stdout, stderr
    for fd in (0, 1, 2):
        try:
            return ioctl_GWINSZ(fd)[1]
        except Exception:
            pass

    # 3. try os.ctermid()
    try:
        fd = os.open(os.ctermid(), os.O_RDONLY)
        try:
            return ioctl_GWINSZ(fd)[1]
        finally:
            os.close(fd)
    except Exception:
        pass

    # 4. try `stty size`
    try:
        process = subprocess.Popen(['stty', 'size'],
                                   shell=False,
                                   stdout=subprocess.PIPE,
                                   stderr=open(os.devnull, 'w'))
        result = process.communicate()
        if process.returncode == 0:
            return tuple(int(x) for x in result[0].split())[1]
    except Exception:
        pass

    # 5. return default fallback value
    return default