sys.stdout.encoding

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.

200 Examples 7

Example 1

Project: blockcheck
Source File: blockcheck.py
View license
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)

Example 2

Project: EventGhost
Source File: test_qrcode.py
View license
    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)

Example 3

Project: synapsePythonClient
Source File: unit_tests.py
View license
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...")

Example 4

Project: radssh
Source File: config.py
View license
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

Example 5

Project: kissanime_dl
Source File: __init__.py
View license
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

Example 6

Project: mimic
Source File: __init__.py
View license
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)

Example 7

Project: psutil
Source File: test_bsd.py
View license
    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)

Example 8

Project: vivisect
Source File: __init__.py
View license
    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)

Example 9

Project: fMBT
Source File: pycosh.py
View license
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

Example 10

Project: pybuilder
Source File: utils.py
View license
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

Example 11

Project: pysslscan
Source File: __init__.py
View license
    @property
    def encoding(self):
        if sys.stdout.encoding is None:
            return ""
        else:
            return sys.stdout.encoding.lower()

Example 12

Project: twx
Source File: twx.py
View license
    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.document, msg.photo, msg.video, msg.sticker, msg.location, msg.contact]):
                self._on_msg_receive(msg=self._to_twx_msg(msg))

Example 13

Project: jirash
Source File: jirashell.py
View license
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

Example 14

Project: nova
Source File: version_manager.py
View license
    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

Example 15

Project: synapsePythonClient
Source File: __main__.py
View license
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'", )

Example 16

Project: psutil
Source File: test_posix.py
View license
    @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))

Example 17

Project: langchangetrack
Source File: common_vocab.py
View license
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)

Example 18

Project: euca2ools
Source File: getconsoleoutput.py
View license
    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

Example 19

Project: slack-utils
Source File: slack-post.py
View license
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

Example 20

Project: fabric
Source File: test_utils.py
View license
@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")

Example 21

Project: gmusic-playlist
Source File: common.py
View license
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)

Example 22

Project: subuser
Source File: print.py
View license
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)

Example 23

Project: scudcloud
Source File: wrapper.py
View license
    @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))

Example 24

Project: fahrplan
Source File: tableprinter.py
View license
    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)

Example 25

Project: peru
Source File: main.py
View license
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)

Example 26

Project: cgstudiomap
Source File: set_name_agi.py
View license
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

Example 27

Project: bde-tools
Source File: sysutil.py
View license
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

Example 28

Project: rtc2git
Source File: shell.py
View license
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

Example 29

Project: econ-project-templates
Source File: Utils.py
View license
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)

Example 30

Project: psutil
Source File: test_windows.py
View license
    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)

Example 31

Project: Pyro4
Source File: echoserver.py
View license
    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

Example 32

Project: psutil
Source File: test_osx.py
View license
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

Example 33

Project: psutil
Source File: test_osx.py
View license
    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)))

Example 34

Project: pyload
Source File: misc.py
View license
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

Example 35

Project: Pyro4
Source File: echoserver.py
View license
    @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"

Example 36

Project: pyconfig
Source File: Executor.py
View license
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)

Example 37

Project: langchangetrack
Source File: freq_count.py
View license
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)

Example 38

Project: tarbell
Source File: utils.py
View license
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)

Example 39

Project: win-unicode-console
Source File: raw_input.py
View license
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)

Example 40

Project: kupfer
Source File: ansiterm.py
View license
		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))

Example 41

Project: kissanime_dl
Source File: vidextract.py
View license
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

Example 42

Project: turses
Source File: utils.py
View license
def encode(string):
    if sys.version_info < (3,):
        try:
            return string.encode(stdout.encoding, 'replace')
        except (AttributeError, TypeError):
            return string
    else:
        return string

Example 43

Project: xraylarch
Source File: strutils.py
View license
    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)

Example 44

Project: alfred-fakeum
Source File: cli.py
View license
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()

Example 45

Project: ddg
Source File: ddg.py
View license
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"

Example 46

View license
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)

Example 47

View license
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)

Example 48

View license
    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()

Example 49

Project: onedrivecmd
Source File: helper_file.py
View license
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))

Example 50

Project: whatlastgenre
Source File: whatlastgenre.py
View license
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