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.
21 Examples
4
Example 1
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
3
Example 2
Project: asyncssh Source File: stream_direct_client.py
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)
3
Example 3
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
3
Example 4
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()
3
Example 5
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()
3
Example 6
Project: yapf Source File: py3compat.py
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))
3
Example 7
def wrapwrite(text):
text = text.encode('utf-8')
try: # Python3
sys.stdout.buffer.write(text)
except AttributeError:
sys.stdout.write(text)
3
Example 8
Project: grab-site Source File: dupespotter.py
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"))
2
Example 9
@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'))
2
Example 10
def wrapwrite(text):
text = text.encode('utf-8')
try: #Python3
sys.stdout.buffer.write(text)
except AttributeError:
sys.stdout.write(text)
0
Example 11
def data_received(self, data, datatype):
# We use sys.stdout.buffer here because we're writing bytes
sys.stdout.buffer.write(data)
0
Example 12
Project: python-erlastic Source File: __init__.py
def port_gen():
while True:
term = encode((yield))
sys.stdout.buffer.write(struct.pack('!I',len(term)))
sys.stdout.buffer.write(term)
0
Example 13
@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")
0
Example 14
def write(out):
try:
sys.stdout.buffer.write(out)
except AttributeError:
sys.stdout.write(out)
0
Example 15
def write(msg):
sys.stdout.buffer.write(msg.encode('utf_8', 'backslashreplace'))
0
Example 16
Project: ansible Source File: cmd_functions.py
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
0
Example 17
Project: spaceship Source File: main.py
def transfer_receive(self, stream_buffer):
sys.stdout.buffer.write(stream_buffer)
0
Example 18
def write_to_stdout(data):
sys.stdout.buffer.write(data + b'\n')
sys.stdout.buffer.flush()
0
Example 19
Project: redbot Source File: webui.py
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)()
0
Example 20
def write(self):
"""
writes `self.output` to disk or stdout
used to write docuement'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'])
0
Example 21
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))