Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
stdin.py177 linesDownload Raw Back to framework
1# Copyright (c) 2000 David Abrahams. Permission to copy, use, modify, sell2# and distribute this software is granted provided this copyright3# notice appears in all copies. This software is provided "as is" without4# express or implied warranty, and with no claim as to its suitability for5# any purpose.6"""Provides a class Stdin which can be used to emulate the regular old7sys.stdin for the PythonWin interactive window. Right now it just pops8up a raw_input() dialog. With luck, someone will integrate it into the9actual PythonWin interactive window someday.10 11WARNING: Importing this file automatically replaces sys.stdin with an12instance of Stdin (below). This is useful because you can just open13Stdin.py in PythonWin and hit the import button to get it set up right14if you don't feel like changing PythonWin's source. To put things back15the way they were, simply use this magic incantation:16    import sys17    sys.stdin = sys.stdin.real_file18"""19import sys20 21try:22    get_input_line = raw_input  # py2x23except NameError:24    get_input_line = input  # py3k25 26 27class Stdin:28    def __init__(self):29        self.real_file = sys.stdin  # NOTE: Likely to be None in py3k30        self.buffer = ""31        self.closed = False32 33    def __getattr__(self, name):34        """Forward most functions to the real sys.stdin for absolute realism."""35        if self.real_file is None:36            raise AttributeError(name)37        return getattr(self.real_file, name)38 39    def isatty(self):40        """Return 1 if the file is connected to a tty(-like) device, else 0."""41        return 142 43    def read(self, size=-1):44        """Read at most size bytes from the file (less if the read45        hits EOF or no more data is immediately available on a pipe,46        tty or similar device). If the size argument is negative or47        omitted, read all data until EOF is reached. The bytes are48        returned as a string object. An empty string is returned when49        EOF is encountered immediately. (For certain files, like ttys,50        it makes sense to continue reading after an EOF is hit.)"""51        result_size = self.__get_lines(size)52        return self.__extract_from_buffer(result_size)53 54    def readline(self, size=-1):55        """Read one entire line from the file. A trailing newline56        character is kept in the string2.6 (but may be absent when a file ends57        with an incomplete line). If the size argument is present and58        non-negative, it is a maximum byte count (including the trailing59        newline) and an incomplete line may be returned. An empty string is60        returned when EOF is hit immediately. Note: unlike stdio's fgets(),61        the returned string contains null characters ('\0') if they occurred62        in the input.63        """64        maximum_result_size = self.__get_lines(size, lambda buffer: "\n" in buffer)65 66        if "\n" in self.buffer[:maximum_result_size]:67            result_size = self.buffer.find("\n", 0, maximum_result_size) + 168            assert result_size > 069        else:70            result_size = maximum_result_size71 72        return self.__extract_from_buffer(result_size)73 74    def __extract_from_buffer(self, character_count):75        """Remove the first character_count characters from the internal buffer and76        return them.77        """78        result = self.buffer[:character_count]79        self.buffer = self.buffer[character_count:]80        return result81 82    def __get_lines(self, desired_size, done_reading=lambda buffer: False):83        """Keep adding lines to our internal buffer until done_reading(self.buffer)84        is true or EOF has been reached or we have desired_size bytes in the buffer.85        If desired_size < 0, we are never satisfied until we reach EOF. If done_reading86        is not supplied, it is not consulted.87 88        If desired_size < 0, returns the length of the internal buffer. Otherwise,89        returns desired_size.90        """91        while not done_reading(self.buffer) and (92            desired_size < 0 or len(self.buffer) < desired_size93        ):94            try:95                self.__get_line()96            except (97                EOFError,98                KeyboardInterrupt,99            ):  # deal with cancellation of get_input_line dialog100                desired_size = len(self.buffer)  # Be satisfied!101 102        if desired_size < 0:103            return len(self.buffer)104        else:105            return desired_size106 107    def __get_line(self):108        """Grab one line from get_input_line() and append it to the buffer."""109        line = get_input_line()110        print(">>>", line)  # echo input to console111        self.buffer = self.buffer + line + "\n"112 113    def readlines(self, *sizehint):114        """Read until EOF using readline() and return a list containing the lines115        thus read. If the optional sizehint argument is present, instead of116        reading up to EOF, whole lines totalling approximately sizehint bytes117        (possibly after rounding up to an internal buffer size) are read.118        """119        result = []120        total_read = 0121        while sizehint == () or total_read < sizehint[0]:122            line = self.readline()123            if line == "":124                break125            total_read = total_read + len(line)126            result.append(line)127        return result128 129 130if __name__ == "__main__":131    test_input = r"""this is some test132input that I am hoping133~134will be very instructive135and when I am done136I will have tested everything.137Twelve and twenty blackbirds138baked in a pie. Patty cake139patty cake so am I.140~141Thirty-five niggling idiots!142Sell you soul to the devil, baby143"""144 145    def fake_raw_input(prompt=None):146        """Replacement for raw_input() which pulls lines out of global test_input.147        For testing only!148        """149        global test_input150        if "\n" not in test_input:151            end_of_line_pos = len(test_input)152        else:153            end_of_line_pos = test_input.find("\n")154        result = test_input[:end_of_line_pos]155        test_input = test_input[end_of_line_pos + 1 :]156        if len(result) == 0 or result[0] == "~":157            raise EOFError()158        return result159 160    get_input_line = fake_raw_input161 162    # Some completely inadequate tests, just to make sure the code's not totally broken163    try:164        x = Stdin()165        print(x.read())166        print(x.readline())167        print(x.read(12))168        print(x.readline(47))169        print(x.readline(3))170        print(x.readlines())171    finally:172        get_input_line = raw_input173else:174    import sys175 176    sys.stdin = Stdin()177 
codekingpro/portable-devtools · Team Ai