Exemplo n.º 1
0
    def _has_fileno(stream: TextIO) -> bool:
        """Returns whether the stream object has a working fileno()

        Suggests whether _redirect_stderr is likely to work.
        """
        try:
            stream.fileno()
        except (AttributeError, OSError, IOError,
                io.UnsupportedOperation):  # pragma: no cover
            return False
        return True
Exemplo n.º 2
0
    def from_pty(cls, stdout: TextIO, term: Optional[str] = None) -> "Vt100_Output":
        """
        Create an Output class from a pseudo terminal.
        (This will take the dimensions by reading the pseudo
        terminal attributes.)
        """
        # Normally, this requires a real TTY device, but people instantiate
        # this class often during unit tests as well. For convenience, we print
        # an error message, use standard dimensions, and go on.
        fd = stdout.fileno()

        if not stdout.isatty() and fd not in cls._fds_not_a_terminal:
            msg = "Warning: Output is not a terminal (fd=%r).\n"
            sys.stderr.write(msg % fd)
            cls._fds_not_a_terminal.add(fd)

        def get_size() -> Size:
            # If terminal (incorrectly) reports its size as 0, pick a
            # reasonable default.  See
            # https://github.com/ipython/ipython/issues/10071
            rows, columns = (None, None)

            # It is possible that `stdout` is no longer a TTY device at this
            # point. In that case we get an `OSError` in the ioctl call in
            # `get_size`. See:
            # https://github.com/prompt-toolkit/python-prompt-toolkit/pull/1021
            try:
                rows, columns = _get_size(stdout.fileno())
            except OSError:
                pass
            return Size(rows=rows or 24, columns=columns or 80)

        return cls(stdout, get_size, term=term)
Exemplo n.º 3
0
    def from_pty(cls, stdout: TextIO, term: Optional[str] = None) -> 'Vt100_Output':
        """
        Create an Output class from a pseudo terminal.
        (This will take the dimensions by reading the pseudo
        terminal attributes.)
        """
        # Normally, this requires a real TTY device, but people instantiate
        # this class often during unit tests as well. For convenience, we print
        # an error message, use standard dimensions, and go on.
        isatty = stdout.isatty()
        fd = stdout.fileno()

        if not isatty and fd not in cls._fds_not_a_terminal:
            msg = 'Warning: Output is not to a terminal (fd=%r).\n'
            sys.stderr.write(msg % fd)
            cls._fds_not_a_terminal.add(fd)

        def get_size() -> Size:
            # If terminal (incorrectly) reports its size as 0, pick a
            # reasonable default.  See
            # https://github.com/ipython/ipython/issues/10071
            rows, columns = (None, None)

            if isatty:
                rows, columns = _get_size(stdout.fileno())
            return Size(rows=rows or 24, columns=columns or 80)

        return cls(stdout, get_size, term=term)
    def from_pty(cls, stdout: TextIO, term: Optional[str] = None) -> 'Vt100_Output':
        """
        Create an Output class from a pseudo terminal.
        (This will take the dimensions by reading the pseudo
        terminal attributes.)
        """
        # Normally, this requires a real TTY device, but people instantiate
        # this class often during unit tests as well. For convenience, we print
        # an error message, use standard dimensions, and go on.
        isatty = stdout.isatty()
        fd = stdout.fileno()

        if not isatty and fd not in cls._fds_not_a_terminal:
            msg = 'Warning: Output is not to a terminal (fd=%r).\n'
            sys.stderr.write(msg % fd)
            cls._fds_not_a_terminal.add(fd)

        def get_size() -> Size:
            # If terminal (incorrectly) reports its size as 0, pick a
            # reasonable default.  See
            # https://github.com/ipython/ipython/issues/10071
            rows, columns = (None, None)

            if isatty:
                rows, columns = _get_size(stdout.fileno())
            return Size(rows=rows or 24, columns=columns or 80)

        return cls(stdout, get_size, term=term)
Exemplo n.º 5
0
def do_cat2(f: TextIO) -> None:
    while True:
        b = os.read(f.fileno(), 1)
        n = os.write(sys.stdout.fileno(), b)

        if n == 0:
            break
Exemplo n.º 6
0
def is_capable(file: TextIO = sys.stderr) -> bool:
    """
    Determine whether we are connected to a capable terminal.
    """
    if not os.isatty(file.fileno()):
        return False
    terminal = os.getenv("TERM", "dumb")
    # Hardcoded list of non-capable terminals.
    return terminal not in ["dumb", "emacs"]
Exemplo n.º 7
0
 def __init__(self, f: TextIO, *, encoding: str = 'utf-8', **kwargs):
     self.f = f
     self.encoding = encoding
     self.file_size = os.fstat(f.fileno()).st_size
     self.progress_bar = progress(total=self.file_size, **kwargs)
     self.size_read = 0
     self._next_tick = 1
     self._next_size = self.file_size // 100
     self._accum_size = 0
Exemplo n.º 8
0
def _is_console(f: t.TextIO) -> bool:
    if not hasattr(f, "fileno"):
        return False

    try:
        fileno = f.fileno()
    except (OSError, io.UnsupportedOperation):
        return False

    handle = msvcrt.get_osfhandle(fileno)
    return bool(GetConsoleMode(handle, byref(DWORD())))
Exemplo n.º 9
0
    def __init__(self, stdin: TextIO) -> None:
        # Test whether the given input object has a file descriptor.
        # (Idle reports stdin to be a TTY, but fileno() is not implemented.)
        try:
            # This should not raise, but can return 0.
            stdin.fileno()
        except io.UnsupportedOperation as e:
            if "idlelib.run" in sys.modules:
                raise io.UnsupportedOperation(
                    "Stdin is not a terminal. Running from Idle is not supported."
                ) from e
            else:
                raise io.UnsupportedOperation(
                    "Stdin is not a terminal.") from e

        # Even when we have a file descriptor, it doesn't mean it's a TTY.
        # Normally, this requires a real TTY device, but people instantiate
        # this class often during unit tests as well. They use for instance
        # pexpect to pipe data into an application. For convenience, we print
        # an error message and go on.
        isatty = stdin.isatty()
        fd = stdin.fileno()

        if not isatty and fd not in Vt100Input._fds_not_a_terminal:
            msg = "Warning: Input is not a terminal (fd=%r).\n"
            sys.stderr.write(msg % fd)
            sys.stderr.flush()
            Vt100Input._fds_not_a_terminal.add(fd)

        #
        self.stdin = stdin

        # Create a backup of the fileno(). We want this to work even if the
        # underlying file is closed, so that `typeahead_hash()` keeps working.
        self._fileno = stdin.fileno()

        self._buffer: List[KeyPress] = []  # Buffer to collect the Key objects.
        self.stdin_reader = PosixStdinReader(self._fileno,
                                             encoding=stdin.encoding)
        self.vt100_parser = Vt100Parser(
            lambda key_press: self._buffer.append(key_press))
Exemplo n.º 10
0
def _get_windows_console_stream(
        f: t.TextIO, encoding: t.Optional[str],
        errors: t.Optional[str]) -> t.Optional[t.TextIO]:
    if (get_buffer is not None and encoding in {"utf-16-le", None}
            and errors in {"strict", None} and _is_console(f)):
        func = _stream_factories.get(f.fileno())
        if func is not None:
            b = getattr(f, "buffer", None)

            if b is None:
                return None

            return func(b)
Exemplo n.º 11
0
    def __init__(self, stdin: TextIO) -> None:
        # Test whether the given input object has a file descriptor.
        # (Idle reports stdin to be a TTY, but fileno() is not implemented.)
        try:
            # This should not raise, but can return 0.
            stdin.fileno()
        except io.UnsupportedOperation:
            if 'idlelib.run' in sys.modules:
                raise io.UnsupportedOperation(
                    'Stdin is not a terminal. Running from Idle is not supported.')
            else:
                raise io.UnsupportedOperation('Stdin is not a terminal.')

        # Even when we have a file descriptor, it doesn't mean it's a TTY.
        # Normally, this requires a real TTY device, but people instantiate
        # this class often during unit tests as well. They use for instance
        # pexpect to pipe data into an application. For convenience, we print
        # an error message and go on.
        isatty = stdin.isatty()
        fd = stdin.fileno()

        if not isatty and fd not in Vt100Input._fds_not_a_terminal:
            msg = 'Warning: Input is not to a terminal (fd=%r).\n'
            sys.stderr.write(msg % fd)
            Vt100Input._fds_not_a_terminal.add(fd)

        #
        self.stdin = stdin

        # Create a backup of the fileno(). We want this to work even if the
        # underlying file is closed, so that `typeahead_hash()` keeps working.
        self._fileno = stdin.fileno()

        self._buffer: List[KeyPress] = []  # Buffer to collect the Key objects.
        self.stdin_reader = PosixStdinReader(self._fileno)
        self.vt100_parser = Vt100Parser(
            lambda key_press: self._buffer.append(key_press))
Exemplo n.º 12
0
def __is_color_terminal(stream: TextIO) -> bool:
    """Determine whether standard output is attached to a color terminal.

    see: https://stackoverflow.com/questions/53574442/how-to-reliably-test-color-capability-of-an-output-terminal-in-python3
    """

    def __handle_nt(fd: int) -> bool:
        import ctypes
        import msvcrt

        ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4

        kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
        hstdout = msvcrt.get_osfhandle(fd)
        mode = ctypes.c_ulong()

        return kernel32.GetConsoleMode(hstdout, ctypes.byref(mode)) and (mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0)

    def __handle_posix(fd: int) -> bool:
        import curses

        try:
            curses.setupterm(fd=fd)
        except curses.error:
            return True
        else:
            return curses.tigetnum('colors') > 0

    def __default(_: int) -> bool:
        return True

    handlers = {
        'nt'    : __handle_nt,
        'posix' : __handle_posix
    }

    handler = handlers.get(os.name, __default)

    return handler(stream.fileno())
Exemplo n.º 13
0
Arquivo: cli.py Projeto: jojonas/pyage
def generate(outfile: typing.TextIO = None) -> None:
    """Generate a new age private/public key pair.

    If no FILENAME is given, the command outputs the key pair to the standard output stream.

    If FILENAME exists, age will warn if the file permissions allow others to read, write or
    execute the file.
    """

    if not outfile:
        outfile = sys.stdout

    key = AgePrivateKey.generate()

    now = datetime.now()
    outfile.write(f"# created: {now:%Y-%m-%dT%H:%M:%S}\n")
    outfile.write("# " + key.public_key().public_string() + "\n")
    outfile.write(key.private_string() + "\n")

    # check permissions if the key is stored in a file
    try:
        stat_result = os.stat(outfile.fileno())
    except io.UnsupportedOperation:
        pass
    else:
        mode = stat_result[stat.ST_MODE]
        if mode & stat.S_IFREG and (mode & stat.S_IRWXO or mode & stat.S_IRWXG):
            perms = mode & 0o777
            print(
                f"Warning: The file permissions ({perms:o}) indicate that other users may have access to the output.",
                file=sys.stderr,
            )

    # print public key to stderr if:
    # - data is going to a file
    # OR: - data is not going to a tty (e.g. piped)
    if (outfile is not sys.stdout) or (not sys.stdout.isatty()):
        print("Public key: " + key.public_key().public_string(), file=sys.stderr)
Exemplo n.º 14
0
 def _lock(lockfp: TextIO) -> None:
     file_size = os.path.getsize(os.path.realpath(lockfp.name))
     msvcrt.locking(lockfp.fileno(), msvcrt.LK_RLCK, file_size)
Exemplo n.º 15
0
 def write_to(self, output: TextIO):
     file_no = output.fileno()
     super().write_to(output)
     output.flush()
     os.fsync(file_no)
Exemplo n.º 16
0
def reduce_textio(obj: TextIO):
    if obj.readable() == obj.writable():
        raise ValueError(
            "TextIO object must be either readable or writable, but not both.")
    fd = Fd(obj.fileno())
    return rebuild_textio, (fd, obj.readable(), obj.writable(), obj.encoding)