Here are the examples of the python api sys.stdout.encoding taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
132 Examples
5
Example 1
Project: EventGhost Source File: test_qrcode.py
def test_print_ascii_stdout(self):
qr = qrcode.QRCode()
stdout_encoding = sys.stdout.encoding
with mock.patch('sys.stdout') as fake_stdout:
# Python 2.6 needs sys.stdout.encoding to be a real string.
sys.stdout.encoding = stdout_encoding
fake_stdout.isatty.return_value = None
self.assertRaises(OSError, qr.print_ascii, tty=True)
self.assertTrue(fake_stdout.isatty.called)
5
Example 2
def print(*args, **kwargs):
if tkusable:
for arg in args:
text.write(str(arg))
text.write("\n")
else:
if args and sys.stdout.encoding != 'UTF-8':
args = [x.translate(trans_table).replace("[☠]", "[FAIL]").replace("[☺]", "[:)]"). \
encode(sys.stdout.encoding, 'replace').decode(sys.stdout.encoding) for x in args
]
__builtins__.print(*args, **kwargs)
3
Example 3
def sysctl(cmdline):
"""Expects a sysctl command with an argument and parse the result
returning only the value of interest.
"""
p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
result = p.communicate()[0].strip().split()[1]
if PY3:
result = str(result, sys.stdout.encoding)
try:
return int(result)
except ValueError:
return result
3
Example 4
Project: peru Source File: main.py
def force_utf8_in_ascii_mode_hack():
'''In systems without a UTF8 locale configured, Python will default to
ASCII mode for stdout and stderr. This causes our fancy display to fail
with encoding errors. In particular, you run into this if you try to run
peru inside of Docker. This is a hack to force emitting UTF8 in that case.
Hopefully it doesn't break anything important.'''
if sys.stdout.encoding == 'ANSI_X3.4-1968':
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8',
buffering=1)
sys.stderr = open(sys.stderr.fileno(), mode='w', encoding='utf8',
buffering=1)
3
Example 5
def encode(msg):
"""This will replace unsuitable characters and use stdout encoding
"""
if isinstance(msg, unicode_string):
return msg.encode(sys.stdout.encoding, "replace")
else:
return bytes(msg)
3
Example 6
def print_result(self, result):
print result.get('instanceId', '')
print result.get('timestamp', '')
output = base64.b64decode(result.get('output') or '')
output = output.decode(sys.stdout.encoding or 'utf-8', 'replace')
output = output.replace(u'\ufffd', u'?')
if not self.args['raw_console_output']:
# Escape control characters
for char, escape in CHAR_ESCAPES.iteritems():
output = output.replace(char, escape)
print output
3
Example 7
def uprint(any):
try:
any.encode(sys.stdout.encoding)
if isinstance(any, str) and sys.version_info < (3, 0, 0):
print(any.encode('utf-8').strip() )
return
print(any)
except UnicodeEncodeError:
return "Unsupported characters in " + sys.stdout.encoding
3
Example 8
def current_version(self, forced_version=None):
if self._current_version is None:
if forced_version is None:
git_version = subprocess.check_output(['git', 'describe', '--tags', '--dirty', '--always'])
console_encoding = sys.stdout.encoding or 'utf-8'
self._current_version = git_version.decode(console_encoding).strip('v').strip()
else:
self._current_version = forced_version
return self._current_version
3
Example 9
Project: subuser Source File: print.py
def printWithoutCrashing(message):
"""
Print to stdout any unicode string and don't crash even if the terminal has a weird encoding.
"""
if not sys.stdout.encoding == "UTF-8": #TODO, utf-16 should also be supported.
try:
preppedMessage = message + u"\n"
preppedMessage = preppedMessage.encode("utf8", 'surrogateescape')
sys.stdout.buffer.write(preppedMessage) #Force utf-8, most terminals can handle it anyways
sys.stdout.flush()
except AttributeError:
message = message.encode("ascii", 'replace')
message = message.decode("ascii")
print(message)
else:
print(message)
3
Example 10
def __str__(self):
result = u""
for key, value in self.items():
if isinstance(value, PropertyResponse):
result += "Resource at %s has %d properties (%s) and %d errors\n" % (
key, len(value), ", ".join([prop[1] for prop in value.keys()]), value.errorCount)
else:
result += "Resource at %s returned " % key + unicode(value)
return result.encode(sys.stdout.encoding or "ascii", "replace")
3
Example 11
def clip(s, length, ellipsis=True):
if len(s) > length:
if ellipsis:
if sys.stdout.encoding in ('UTF-8',):
s = s[:length-1] + u'\u2026'
else:
s = s[:length-3] + '...'
else:
s = s[:length]
return s
3
Example 12
def __init__(self, widths, separator=' '):
"""Constructor for table printer.
Args:
widths: Tuple containing the width for each column.
separator: The column separator (default ' ').
"""
self.widths = widths
self.separator = separator
try:
self.encoding = sys.stdout.encoding or 'utf-8'
except AttributeError:
self.encoding = 'utf-8'
logging.debug('Using output encoding %s' % self.encoding)
3
Example 13
def __init__(self):
self.encoding = sys.stdout.encoding
self.hconsole = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
self.cursor_history = []
self.orig_sbinfo = CONSOLE_SCREEN_BUFFER_INFO()
self.orig_csinfo = CONSOLE_CURSOR_INFO()
windll.kernel32.GetConsoleScreenBufferInfo(self.hconsole, byref(self.orig_sbinfo))
windll.kernel32.GetConsoleCursorInfo(hconsole, byref(self.orig_csinfo))
3
Example 14
def addText(self, text, tag=None):
"""
Add text to the canvas with a specified tag.
NOTE: Implementors should probably check _canv_scrolled to
decide if they should scroll to the end of the view...
"""
if sys.stdout.encoding:
text = text.encode(sys.stdout.encoding, 'replace')
sys.stdout.write(text)
3
Example 15
Project: fabric Source File: test_utils.py
@mock_streams('stdout')
def test_puts_with_encoding_type_none_output():
"""
puts() should print unicode output without a stream encoding
"""
s = u"string!"
output.user = True
sys.stdout.encoding = None
puts(s, show_prefix=False)
eq_(sys.stdout.getvalue(), s + "\n")
3
Example 16
Project: pyconfig Source File: Executor.py
def Invoke(call_args, shell_state=False):
error = 0
output = None
try:
output = subprocess.check_output(call_args, shell=shell_state, stderr=DEVNULL).decode(sys.stdout.encoding)
except subprocess.CalledProcessError as exception:
output = exception.output.decode(sys.stdout.encoding)
error = exception.returncode
return (output, error)
3
Example 17
Project: psutil Source File: test_posix.py
@unittest.skipIf(SUNOS, "unreliable on SUNOS")
@unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
def test_nic_names(self):
p = subprocess.Popen("ifconfig -a", shell=1, stdout=subprocess.PIPE)
output = p.communicate()[0].strip()
if p.returncode != 0:
raise unittest.SkipTest('ifconfig returned no output')
if PY3:
output = str(output, sys.stdout.encoding)
for nic in psutil.net_io_counters(pernic=True).keys():
for line in output.split():
if line.startswith(nic):
break
else:
self.fail(
"couldn't find %s nic in 'ifconfig -a' output\n%s" % (
nic, output))
3
Example 18
def ask_user(query, results):
"""Ask the user to choose from a list of results."""
print("%-8s %-6s got %2d results. Which is it?"
% (query.dapr.name, query.type, len(results)))
for i, result in enumerate(results, start=1):
info = result['info'].encode(sys.stdout.encoding, errors='replace')
print("#%2d: %s" % (i, info))
while True:
try:
num = int(raw_input("Please choose #[1-%d] (0 to skip): "
% len(results)))
except ValueError:
num = None
except EOFError:
num = 0
print()
if num in range(len(results) + 1):
break
return [results[num - 1]] if num else results
3
Example 19
def echo(self, message):
"""return the message"""
if self._verbose:
message_str = repr(message).encode(sys.stdout.encoding, errors="replace").decode(sys.stdout.encoding)
print("%s - echo: %s" % (time.asctime(), message_str))
return message
3
Example 20
Project: mimic Source File: __init__.py
def get_writer():
"""
:return: A codec writer for stdout. Necessary for output piping to work.
"""
from codecs import getwriter
from sys import stdout
if version_info >= (3,):
return stdout
return getwriter(stdout.encoding or 'utf-8')(stdout)
3
Example 21
Project: pyphantomjs Source File: phantom.py
@outputEncoding.setter
def outputEncoding(self, encoding):
self.m_outputEncoding = Encode(encoding, self.m_outputEncoding.encoding)
sys.stdout.encoding = self.m_outputEncoding.encoding
sys.stdout.encode_to = self.m_outputEncoding.encoding
sys.stderr.encoding = self.m_outputEncoding.encoding
sys.stdout.encode_to = self.m_outputEncoding.encoding
3
Example 22
def execute_cmd(cmd):
"""str->int
Execute a command,
send the command output to the screen,
give a simple warning if the command failed,
return the exit code of the command.
"""
os.system(cmd.decode("utf-8").encode(sys.stdout.encoding))
3
Example 23
def process_update(self, update: botapi.Update):
try:
print(update)
except Exception:
import sys
print(update.__str__().encode().decode(sys.stdout.encoding))
msg = update.message
if msg:
if any([msg.text, msg.audio, msg.docuement, msg.photo, msg.video, msg.sticker, msg.location, msg.contact]):
self._on_msg_receive(msg=self._to_twx_msg(msg))
3
Example 24
Project: rtc2git Source File: shell.py
def getoutput(command, stripped=True):
shout_command_to_log(command)
try:
outputasbytestring = check_output(command, shell=True)
output = outputasbytestring.decode(sys.stdout.encoding).splitlines()
except CalledProcessError as e:
shouter.shout(e)
output = ""
if not stripped:
return output
else:
lines = []
for line in output:
strippedline = line.strip()
if strippedline:
lines.append(strippedline)
return lines
3
Example 25
def execute_from_command_line(argv=None):
"""A simple method that runs a Command."""
if sys.stdout.encoding is None:
print('please set python env PYTHONIOENCODING=UTF-8, example: '
'export PYTHONIOENCODING=UTF-8, when writing to stdout',
file=sys.stderr)
exit(1)
command = Command(argv)
command.execute()
3
Example 26
def encode(string):
if sys.version_info < (3,):
try:
return string.encode(stdout.encoding, 'replace')
except (AttributeError, TypeError):
return string
else:
return string
3
Example 27
def stdout_encode(s):
if isinstance(s, bytes):
return s
encoding = sys.stdout.encoding
errors = sys.stdout.errors
if errors is not None:
return s.encode(encoding, errors)
else:
return s.encode(encoding)
3
Example 28
def main(args):
encoding = sys.stdout.encoding or 'utf-8'
f = open(args.filename)
fd = nltk.FreqDist()
for line in f:
for sent in nltk.sent_tokenize(line):
for word in nltk.word_tokenize(sent):
fd[word] += 1
for w, count in fd.most_common():
tup = u"{} {}".format(w, count)
print tup.encode(encoding)
3
Example 29
def _shell_soe(cmd):
try:
p = subprocess.Popen(cmd, shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
status = p.returncode
except OSError:
status, out, err = None, None, None
if out != None and sys.stdout.encoding:
out = out.decode(sys.stdout.encoding).encode("utf-8")
if err != None and sys.stderr.encoding:
err = err.decode(sys.stderr.encoding).encode("utf-8")
return status, out, err
3
Example 30
def test_unicode_output():
encoding = sys.stdout.encoding if hasattr(sys.stdout, 'encoding') else 'no encoding'
print("\nPython thinks your character encoding is:", encoding)
if encoding and encoding.lower() in ['utf-8', 'utf-16']:
print("ȧƈƈḗƞŧḗḓ uʍop-ǝpısdn ŧḗẋŧ ƒǿř ŧḗşŧīƞɠ")
else:
print("can't display unicode, skipping test_unicode_output...")
3
Example 31
@property
def encoding(self):
if sys.stdout.encoding is None:
return ""
else:
return sys.stdout.encoding.lower()
3
Example 32
def execute_command(command):
stdout = NamedTemporaryFile()
stderr = NamedTemporaryFile()
start = datetime.now()
proc = subprocess.Popen(command, stdout=stdout, stderr=stderr, shell=True)
proc.communicate()
delta = datetime.now() - start
stdout_data = read_and_truncate(stdout, encoding=sys.stdout.encoding)
stderr_data = read_and_truncate(stderr, encoding=sys.stderr.encoding)
stdout.close()
stderr.close()
return proc.returncode, stdout_data, stderr_data, delta
3
Example 33
def test_process_create_time(self):
cmdline = "ps -o lstart -p %s" % self.pid
p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
output = p.communicate()[0]
if PY3:
output = str(output, sys.stdout.encoding)
start_ps = output.replace('STARTED', '').strip()
start_psutil = psutil.Process(self.pid).create_time()
start_psutil = time.strftime("%a %b %e %H:%M:%S %Y",
time.localtime(start_psutil))
self.assertEqual(start_ps, start_psutil)
3
Example 34
Project: scudcloud Source File: wrapper.py
@QtCore.pyqtSlot(bool)
def pasted(self, checked):
clipboard = QApplication.clipboard()
mime = clipboard.mimeData()
if mime.hasImage():
pixmap = clipboard.pixmap()
byteArray = QByteArray()
buffer = QBuffer(byteArray)
pixmap.save(buffer, "PNG")
self.call("setClipboard", str(byteArray.toBase64(), sys.stdout.encoding))
3
Example 35
def test_process_create_time(self):
cmdline = "ps -o lstart -p %s" % self.pid
p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
output = p.communicate()[0]
if PY3:
output = str(output, sys.stdout.encoding)
start_ps = output.replace('STARTED', '').strip()
hhmmss = start_ps.split(' ')[-2]
year = start_ps.split(' ')[-1]
start_psutil = psutil.Process(self.pid).create_time()
self.assertEqual(
hhmmss,
time.strftime("%H:%M:%S", time.localtime(start_psutil)))
self.assertEqual(
year,
time.strftime("%Y", time.localtime(start_psutil)))
3
Example 36
Project: xraylarch Source File: strutils.py
def bytes2str(s):
if isinstance(s, str):
return s
elif isinstance(s, bytes):
return s.decode(sys.stdout.encoding)
return str(s, sys.stdout.encoding)
3
Example 37
def test_nic_names(self):
p = subprocess.Popen(['ipconfig', '/all'], stdout=subprocess.PIPE)
out = p.communicate()[0]
if PY3:
out = str(out, sys.stdout.encoding or sys.getfilesystemencoding())
nics = psutil.net_io_counters(pernic=True).keys()
for nic in nics:
if "pseudo-interface" in nic.replace(' ', '-').lower():
continue
if nic not in out:
self.fail(
"%r nic wasn't found in 'ipconfig /all' output" % nic)
3
Example 38
def log(message, nl = True):
if nl:
message += os.linesep
sys.stdout.write(message.encode(sys.stdout.encoding, errors='replace'))
if logfile:
logfile.write(message)
3
Example 39
Project: econ-project-templates Source File: Utils.py
def split_path_msys(path):
if path.startswith(('/', '\\')) and not path.startswith(('\\', '\\\\')):
# msys paths can be in the form /usr/bin
global msysroot
if not msysroot:
# msys has python 2.7 or 3, so we can use this
msysroot = subprocess.check_output(['cygpath', '-w', '/']).decode(sys.stdout.encoding or 'iso8859-1')
msysroot = msysroot.strip()
path = os.path.normpath(msysroot + os.sep + path)
return split_path_win32(path)
3
Example 40
def shell_command(cmd):
"""Execute and return the output of a shell command.
"""
kw = {}
kw['shell'] = isinstance(cmd, str)
kw['stdout'] = kw['stderr'] = subprocess.PIPE
(out, err) = subprocess.Popen(cmd, **kw).communicate()
if not isinstance(out, str):
out = out.decode(sys.stdout.encoding or 'iso8859-1')
return out
3
Example 41
Project: Pyro4 Source File: echoserver.py
@Pyro4.oneway
def oneway_echo(self, message):
"""just like echo, but oneway; the client won't wait for response"""
if self._verbose:
message_str = repr(message).encode(sys.stdout.encoding, errors="replace").decode(sys.stdout.encoding)
print("%s - oneway_echo: %s" % (time.asctime(), message_str))
return "bogus return value"
3
Example 42
def decode(value, encoding=None, errors='strict'):
"""
Encoded string (default to own system encoding) -> unicode string
"""
if type(value) is str:
res = unicode(value, encoding or get_console_encoding(sys.stdout.encoding), errors)
elif type(value) is unicode:
res = value
else:
res = unicode(value)
return res
3
Example 43
def print_result(result):
"""Print the result, ascii encode if necessary"""
try:
print result
except UnicodeEncodeError:
if sys.stdout.encoding:
print result.encode(sys.stdout.encoding, 'replace')
else:
print result.encode('utf8')
except:
print "Unexpected error attempting to print result"
3
Example 44
Project: cgstudiomap Source File: set_name_agi.py
def stdout_write(string):
'''Wrapper on sys.stdout.write'''
sys.stdout.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace'))
sys.stdout.flush()
# When we output a command, we get an answer "200 result=1" on stdin
# Purge stdin to avoid these Asterisk error messages :
# utils.c ast_carefulwrite: write() returned error: Broken pipe
sys.stdin.readline()
return True
3
Example 45
def puts(s='', newline=True, stream=STDOUT):
"""
Wrap puts to avoid getting called twice by Werkzeug reloader.
"""
if not is_werkzeug_process():
try:
return _puts(s, newline, stream)
except UnicodeEncodeError:
return _puts(s.encode(sys.stdout.encoding), newline, stream)
3
Example 46
Project: pybuilder Source File: utils.py
def execute_command_and_capture_output(*command_and_arguments):
process_handle = Popen(command_and_arguments, stdout=PIPE, stderr=PIPE)
stdout, stderr = process_handle.communicate()
stdout, stderr = stdout.decode(sys.stdout.encoding or 'utf-8'), stderr.decode(sys.stderr.encoding or 'utf-8')
process_return_code = process_handle.returncode
return process_return_code, stdout, stderr
3
Example 47
Project: radssh Source File: config.py
def load_default_settings():
'''Load just the default settings, ignoring system and user settings files'''
# Start with the default_config settings from the module
defaults = StringIO(default_config)
settings = load_settings_file(defaults)
# Fill default username and character encodings from derived values
# not in the default_config template string.
if 'username' not in settings:
settings['username'] = os.environ.get(
'SSH_USER', os.environ.get('USER', os.environ.get('USERNAME', 'default')))
if 'character_encoding' not in settings:
if sys.stdout.encoding:
settings['character_encoding'] = sys.stdout.encoding
else:
settings['character_encoding'] = 'UTF-8'
return settings
3
Example 48
def test_encoding(args, syn):
import locale
import platform
print("python version = ", platform.python_version())
print("sys.stdout.encoding = ", sys.stdout.encoding if hasattr(sys.stdout, 'encoding') else 'no encoding attribute')
print("sys.stdout.isatty() = ", sys.stdout.isatty())
print("locale.getpreferredencoding() =", locale.getpreferredencoding())
print("sys.getfilesystemencoding() = ", sys.getfilesystemencoding())
print("PYTHONIOENCODING = ", os.environ.get("PYTHONIOENCODING", None))
print("latin1 chars = D\xe9j\xe0 vu, \xfcml\xf8\xfats")
print("Some non-ascii chars = '\u0227\u0188\u0188\u1e17\u019e\u0167\u1e17\u1e13 u\u028dop-\u01ddp\u0131sdn \u0167\u1e17\u1e8b\u0167 \u0192\u01ff\u0159 \u0167\u1e17\u015f\u0167\u012b\u019e\u0260'", )
3
Example 49
def main(args):
encoding = sys.stdout.encoding or 'utf-8'
common_vocab = None
list_of_files = glob(args.filepattern)
for fname in list_of_files:
file_vocab = set()
f = open(fname)
for line in f:
for sent in nltk.sent_tokenize(line):
for word in nltk.word_tokenize(sent):
file_vocab.add(word)
if common_vocab == None:
common_vocab = file_vocab
else:
common_vocab = common_vocab & file_vocab
f.close()
for w in common_vocab:
print w.encode(encoding)
3
Example 50
Project: pythonVSCode Source File: visualstudio_py_repl.py
def execute_process_work_item(self):
try:
from subprocess import Popen, PIPE, STDOUT
import codecs
out_codec = codecs.lookup(sys.stdout.encoding)
proc = Popen(
'"%s" %s' % (self.current_code, self.current_args),
stdout=PIPE,
stderr=STDOUT,
bufsize=0,
)
for line in proc.stdout:
print(out_codec.decode(line, 'replace')[0].rstrip('\r\n'))
except Exception:
traceback.print_exc()