sys.stdout.buffer.write

Here are the examples of the python api sys.stdout.buffer.write taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

36 Examples 7

Example 1

Project: pre-commit
Source File: main.py
View license
def func():
    # Intentionally write mixed encoding to the output.  This should not crash
    # pre-commit and should write bytes to the output.
    sys.stdout.buffer.write('☃'.encode('UTF-8') + '²'.encode('latin1') + b'\n')
    # Return 1 to trigger printing
    return 1

Example 2

Project: ptyprocess
Source File: ptyprocess.py
View license
        @staticmethod
        def write_to_stdout(b):
            try:
                return sys.stdout.buffer.write(b)
            except AttributeError:
                # If stdout has been replaced, it may not have .buffer
                return sys.stdout.write(b.decode('ascii', 'replace'))

Example 3

Project: asyncssh
Source File: stream_direct_client.py
View license
async def run_client():
    async with asyncssh.connect('localhost') as conn:
        reader, writer = await conn.open_connection('www.google.com', 80)

        # By default, TCP connections send and receive bytes
        writer.write(b'HEAD / HTTP/1.0\r\n\r\n')
        writer.write_eof()

        # We use sys.stdout.buffer here because we're writing bytes
        response = await reader.read()
        sys.stdout.buffer.write(response)

Example 4

Project: hug
Source File: interface.py
View license
    def output(self, data):
        """Outputs the provided data using the transformations and output format specified for this CLI endpoint"""
        if self.transform:
            data = self.transform(data)
        if hasattr(data, 'read'):
            data = data.read().decode('utf8')
        if data is not None:
            data = self.outputs(data)
            if data:
                sys.stdout.buffer.write(data)
                if not data.endswith(b'\n'):
                    sys.stdout.buffer.write(b'\n')
        return data

Example 5

Project: vj4
Source File: fs.py
View license
async def cat(file_id: objectid.ObjectId):
  """Cat a file. Note: this method will block the thread."""
  grid_out = await get(file_id)
  buf = await grid_out.read()
  while buf:
    sys.stdout.buffer.write(buf)
    buf = await grid_out.read()

Example 6

Project: gitsome
Source File: html2text.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try: #Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 7

Project: wp2md
Source File: html2text.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try: #Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 8

Project: curlbomb
Source File: server.py
View license
    def data_received(self, data):
        """Handle incoming PUT data"""
        if self._log_post_backs:
            sys.stdout.buffer.write(data)
        if self._postback_log_file:
            self._postback_log_file.write(data)
            self._postback_log_file.flush()

Example 9

Project: yapf
Source File: py3compat.py
View license
def EncodeAndWriteToStdout(s, encoding='utf-8'):
  """Encode the given string and emit to stdout.

  The string may contain non-ascii characters. This is a problem when stdout is
  redirected, because then Python doesn't know the encoding and we may get a
  UnicodeEncodeError.

  Arguments:
    s: (string) The string to encode.
    encoding: (string) The encoding of the string.
  """
  if PY3:
    sys.stdout.buffer.write(codecs.encode(s, encoding))
  else:
    sys.stdout.write(s.encode(encoding))

Example 10

Project: 2015.hackatbrown.org
Source File: html2text.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try: #Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 11

Project: PyDataset
Source File: html2text.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try: #Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 12

Project: jabbapylib
Source File: html2text.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try: #Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 13

Project: FanFicFare
Source File: utils.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try:  # Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 14

Project: FanFicFare
Source File: utils.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try:  # Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 15

Project: grab-site
Source File: dupespotter.py
View license
def compare_bodies(body1, body2, url1, url2):
	# TODO: handle non-utf-8 bodies
	for line in difflib.unified_diff(
		body1.decode("utf-8", "replace").splitlines(keepends=True),
		body2.decode("utf-8", "replace").splitlines(keepends=True),
		fromfile=url1,
		tofile=url2):
		if not "\n" in line:
			line += "\n"
		sys.stdout.buffer.write(line.encode("utf-8"))

Example 16

Project: grab-site
Source File: dupespotter.py
View license
def compare_bodies(body1, body2, url1, url2):
	# TODO: handle non-utf-8 bodies
	for line in difflib.unified_diff(
		body1.decode("utf-8", "replace").splitlines(keepends=True),
		body2.decode("utf-8", "replace").splitlines(keepends=True),
		fromfile=url1,
		tofile=url2):
		if not "\n" in line:
			line += "\n"
		sys.stdout.buffer.write(line.encode("utf-8"))

Example 17

Project: ArchiveBot
Source File: dupespotter.py
View license
def compare_bodies(body1, body2, url1, url2):
	# TODO: handle non-utf-8 bodies
	for line in difflib.unified_diff(
		body1.decode("utf-8", "replace").splitlines(keepends=True),
		body2.decode("utf-8", "replace").splitlines(keepends=True),
		fromfile=url1,
		tofile=url2):
		if not "\n" in line:
			line += "\n"
		sys.stdout.buffer.write(line.encode("utf-8"))

Example 18

Project: ArchiveBot
Source File: dupespotter.py
View license
def compare_bodies(body1, body2, url1, url2):
	# TODO: handle non-utf-8 bodies
	for line in difflib.unified_diff(
		body1.decode("utf-8", "replace").splitlines(keepends=True),
		body2.decode("utf-8", "replace").splitlines(keepends=True),
		fromfile=url1,
		tofile=url2):
		if not "\n" in line:
			line += "\n"
		sys.stdout.buffer.write(line.encode("utf-8"))

Example 19

Project: html2text
Source File: html2text.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try: #Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 20

Project: RedditBots
Source File: html2text.py
View license
def wrapwrite(text):
    text = text.encode('utf-8')
    try: #Python3
        sys.stdout.buffer.write(text)
    except AttributeError:
        sys.stdout.write(text)

Example 21

Project: asyncssh
Source File: direct_client.py
View license
    def data_received(self, data, datatype):
        # We use sys.stdout.buffer here because we're writing bytes
        sys.stdout.buffer.write(data)

Example 22

Project: python-erlastic
Source File: __init__.py
View license
def port_gen():
  while True:
    term = encode((yield))
    sys.stdout.buffer.write(struct.pack('!I',len(term)))
    sys.stdout.buffer.write(term)

Example 23

Project: hbmqtt
Source File: sub_script.py
View license
@asyncio.coroutine
def do_sub(client, arguments):

    try:
        yield from client.connect(uri=arguments['--url'],
                                  cleansession=arguments['--clean-session'],
                                  cafile=arguments['--ca-file'],
                                  capath=arguments['--ca-path'],
                                  cadata=arguments['--ca-data'])
        qos = _get_qos(arguments)
        filters=[]
        for topic in arguments['-t']:
            filters.append((topic, qos))
        yield from client.subscribe(filters)
        if arguments['-n']:
            max_count = int(arguments['-n'])
        else:
            max_count = None
        count = 0
        while True:
            if max_count and count >= max_count:
                break
            try:
                message = yield from client.deliver_message()
                count += 1
                sys.stdout.buffer.write(message.publish_packet.data)
                sys.stdout.write('\n')
            except MQTTException:
                logger.debug("Error reading packet")
        yield from client.disconnect()
    except KeyboardInterrupt:
        yield from client.disconnect()
    except ConnectException as ce:
        logger.fatal("connection to '%s' failed: %r" % (arguments['--url'], ce))
    except asyncio.CancelledError as cae:
        logger.fatal("Publish canceled due to prvious error")

Example 24

Project: freedoom
Source File: bootstrap.py
View license
def write(out):
    try:
        sys.stdout.buffer.write(out)
    except AttributeError:
        sys.stdout.write(out)

Example 25

View license
    def write(msg):
        sys.stdout.buffer.write(msg.encode('utf_8', 'backslashreplace'))

Example 26

View license
    def write(msg):
        sys.stdout.buffer.write(msg.encode('utf_8', 'backslashreplace'))

Example 27

Project: ansible
Source File: cmd_functions.py
View license
def run_cmd(cmd, live=False, readsize=10):

    #readsize = 10

    # On python2, shlex needs byte strings
    if PY2:
        cmd = to_bytes(cmd, errors='surrogate_or_strict')
    cmdargs = shlex.split(cmd)

    # subprocess should be passed byte strings.  (on python2.6 it must be
    # passed byte strtings)
    cmdargs = [to_bytes(a, errors='surrogate_or_strict') for a in cmdargs]

    p = subprocess.Popen(cmdargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    stdout = b''
    stderr = b''
    rpipes = [p.stdout, p.stderr]
    while True:
        rfd, wfd, efd = select.select(rpipes, [], rpipes, 1)

        if p.stdout in rfd:
            dat = os.read(p.stdout.fileno(), readsize)
            if live:
                # On python3, stdout has a codec to go from text type to bytes
                if PY3:
                    sys.stdout.buffer.write(dat)
                else:
                    sys.stdout.write(dat)
            stdout += dat
            if dat == b'':
                rpipes.remove(p.stdout)
        if p.stderr in rfd:
            dat = os.read(p.stderr.fileno(), readsize)
            stderr += dat
            if live:
                # On python3, stdout has a codec to go from text type to bytes
                if PY3:
                    sys.stdout.buffer.write(dat)
                else:
                    sys.stdout.write(dat)
            if dat == b'':
                rpipes.remove(p.stderr)
        # only break out if we've emptied the pipes, or there is nothing to
        # read from and the process has finished.
        if (not rpipes or not rfd) and p.poll() is not None:
            break
        # Calling wait while there are still pipes to read can cause a lock
        elif not rpipes and p.poll() == None:
            p.wait()

    return p.returncode, stdout, stderr

Example 28

Project: ansible
Source File: cmd_functions.py
View license
def run_cmd(cmd, live=False, readsize=10):

    #readsize = 10

    # On python2, shlex needs byte strings
    if PY2:
        cmd = to_bytes(cmd, errors='surrogate_or_strict')
    cmdargs = shlex.split(cmd)

    # subprocess should be passed byte strings.  (on python2.6 it must be
    # passed byte strtings)
    cmdargs = [to_bytes(a, errors='surrogate_or_strict') for a in cmdargs]

    p = subprocess.Popen(cmdargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    stdout = b''
    stderr = b''
    rpipes = [p.stdout, p.stderr]
    while True:
        rfd, wfd, efd = select.select(rpipes, [], rpipes, 1)

        if p.stdout in rfd:
            dat = os.read(p.stdout.fileno(), readsize)
            if live:
                # On python3, stdout has a codec to go from text type to bytes
                if PY3:
                    sys.stdout.buffer.write(dat)
                else:
                    sys.stdout.write(dat)
            stdout += dat
            if dat == b'':
                rpipes.remove(p.stdout)
        if p.stderr in rfd:
            dat = os.read(p.stderr.fileno(), readsize)
            stderr += dat
            if live:
                # On python3, stdout has a codec to go from text type to bytes
                if PY3:
                    sys.stdout.buffer.write(dat)
                else:
                    sys.stdout.write(dat)
            if dat == b'':
                rpipes.remove(p.stderr)
        # only break out if we've emptied the pipes, or there is nothing to
        # read from and the process has finished.
        if (not rpipes or not rfd) and p.poll() is not None:
            break
        # Calling wait while there are still pipes to read can cause a lock
        elif not rpipes and p.poll() == None:
            p.wait()

    return p.returncode, stdout, stderr

Example 29

Project: spaceship
Source File: main.py
View license
    def transfer_receive(self, stream_buffer):
        sys.stdout.buffer.write(stream_buffer)

Example 30

Project: hyper
Source File: compat.py
View license
    def write_to_stdout(data):
        sys.stdout.buffer.write(data + b'\n')
        sys.stdout.buffer.flush()

Example 31

Project: hyper
Source File: compat.py
View license
    def write_to_stdout(data):
        sys.stdout.buffer.write(data + b'\n')
        sys.stdout.buffer.flush()

Example 32

Project: redbot
Source File: webui.py
View license
def cgi_main():
    """Run REDbot as a CGI Script."""
    def out(inbytes):
        try:
            sys.stdout.buffer.write(inbytes)             
            sys.stdout.flush()
        except IOError: 
            pass
            
    ui_uri = "%s://%s%s%s" % (
        'HTTPS' in os.environ and "https" or "http",
        os.environ.get('HTTP_HOST'),
        os.environ.get('SCRIPT_NAME'),
        os.environ.get('PATH_INFO', ''))
    method = os.environ.get('REQUEST_METHOD').encode(Config.charset)
    query_string = os.environ.get('QUERY_STRING', "").encode(Config.charset)

    def response_start(code, phrase, res_hdrs):
        out_v = [b"Status: %s %s" % (code, phrase)]
        for k, v in res_hdrs:
            out_v.append(b"%s: %s" % (k, v))
        out_v.append(b"")
        out_v.append(b"")
        out(b"\n".join(out_v))

    freak_ceiling = 20000
    def response_body(chunk):
        rest = None
        if len(chunk) > freak_ceiling:
            rest = chunk[freak_ceiling:]
            chunk = chunk[:freak_ceiling]
        out(chunk)
        if rest:
            response_body(rest)

    def response_done(trailers):
        thor.schedule(0, thor.stop)
    try:
        RedWebUi(Config, ui_uri, method, query_string,
                 response_start, response_body, response_done)
        thor.run()
    except:
        except_handler_factory(Config, qs=query_string)()

Example 33

Project: redbot
Source File: webui.py
View license
def cgi_main():
    """Run REDbot as a CGI Script."""
    def out(inbytes):
        try:
            sys.stdout.buffer.write(inbytes)             
            sys.stdout.flush()
        except IOError: 
            pass
            
    ui_uri = "%s://%s%s%s" % (
        'HTTPS' in os.environ and "https" or "http",
        os.environ.get('HTTP_HOST'),
        os.environ.get('SCRIPT_NAME'),
        os.environ.get('PATH_INFO', ''))
    method = os.environ.get('REQUEST_METHOD').encode(Config.charset)
    query_string = os.environ.get('QUERY_STRING', "").encode(Config.charset)

    def response_start(code, phrase, res_hdrs):
        out_v = [b"Status: %s %s" % (code, phrase)]
        for k, v in res_hdrs:
            out_v.append(b"%s: %s" % (k, v))
        out_v.append(b"")
        out_v.append(b"")
        out(b"\n".join(out_v))

    freak_ceiling = 20000
    def response_body(chunk):
        rest = None
        if len(chunk) > freak_ceiling:
            rest = chunk[freak_ceiling:]
            chunk = chunk[:freak_ceiling]
        out(chunk)
        if rest:
            response_body(rest)

    def response_done(trailers):
        thor.schedule(0, thor.stop)
    try:
        RedWebUi(Config, ui_uri, method, query_string,
                 response_start, response_body, response_done)
        thor.run()
    except:
        except_handler_factory(Config, qs=query_string)()

Example 34

Project: panzer
Source File: document.py
View license
    def write(self):
        """
        writes `self.output` to disk or stdout
        used to write document's output
        """
        # case 1: pdf or binary file as output
        if self.options['pandoc']['pdf_output'] \
        or self.options['pandoc']['write'] in const.BINARY_WRITERS:
            info.log('DEBUG', 'panzer', 'output to binary file by pandoc')
            return
        # case 2: no output generated
        if not self.output and self.options['pandoc']['write'] != 'rtf':
            # hack for rtf writer to get around issue:
            # https://github.com/jgm/pandoc/issues/1732
            # probably no longer needed as now fixed in pandoc 1.13.2
            info.log('DEBUG', 'panzer', 'no output to write')
            return
        # case 3: stdout as output
        if self.options['pandoc']['output'] == '-':
            sys.stdout.buffer.write(self.output.encode(const.ENCODING))
            sys.stdout.flush()
            info.log('DEBUG', 'panzer', 'output written stdout by panzer')
        # case 4: output to file
        else:
            with open(self.options['pandoc']['output'], 'w',
                      encoding=const.ENCODING) as output_file:
                output_file.write(self.output)
                output_file.flush()
            info.log('INFO', 'panzer', 'output written to "%s"'
                     % self.options['pandoc']['output'])

Example 35

Project: panzer
Source File: document.py
View license
    def write(self):
        """
        writes `self.output` to disk or stdout
        used to write document's output
        """
        # case 1: pdf or binary file as output
        if self.options['pandoc']['pdf_output'] \
        or self.options['pandoc']['write'] in const.BINARY_WRITERS:
            info.log('DEBUG', 'panzer', 'output to binary file by pandoc')
            return
        # case 2: no output generated
        if not self.output and self.options['pandoc']['write'] != 'rtf':
            # hack for rtf writer to get around issue:
            # https://github.com/jgm/pandoc/issues/1732
            # probably no longer needed as now fixed in pandoc 1.13.2
            info.log('DEBUG', 'panzer', 'no output to write')
            return
        # case 3: stdout as output
        if self.options['pandoc']['output'] == '-':
            sys.stdout.buffer.write(self.output.encode(const.ENCODING))
            sys.stdout.flush()
            info.log('DEBUG', 'panzer', 'output written stdout by panzer')
        # case 4: output to file
        else:
            with open(self.options['pandoc']['output'], 'w',
                      encoding=const.ENCODING) as output_file:
                output_file.write(self.output)
                output_file.flush()
            info.log('INFO', 'panzer', 'output written to "%s"'
                     % self.options['pandoc']['output'])

Example 36

Project: pelita
Source File: create_maze.py
View license
def main(argv):
    parser = optparse.OptionParser()

    parser.add_option("-y", "--height", type="int", default=16,
                      help=default("height of the maze"))
    parser.add_option("-x", "--width", type="int", default=32,
                      help=default("width of the maze"))

    parser.add_option("-f", "--food", type="int", default=30,
                      help=default("number of food dots for each team"))

    parser.add_option("--seed", type="int", default=None,
                      help="fix the random seed used to generate the maze")
    parser.add_option("--dead-ends", action="store_true", dest="dead_ends",
                      default=False,
                      help="allow dead ends in the maze")
    parser.add_option("--no-dead-ends", action="store_false", dest="dead_ends",
                      help="do not allow dead ends in the maze [Default]")

    opts, args = parser.parse_args()
    sys.stdout.buffer.write(get_new_maze(opts.height, opts.width, nfood=opts.food,
                            seed=opts.seed, dead_ends=opts.dead_ends))