Python sys.__stderr__() Examples

The following are 30 code examples of sys.__stderr__(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: rpc.py    From oss-ftp with MIT License 6 votes vote down vote up
def handle_error(self, request, client_address):
        """Override TCPServer method

        Error message goes to __stderr__.  No error message if exiting
        normally or socket raised EOF.  Other exceptions not handled in
        server code will cause os._exit.

        """
        try:
            raise
        except SystemExit:
            raise
        except:
            erf = sys.__stderr__
            print>>erf, '\n' + '-'*40
            print>>erf, 'Unhandled server exception!'
            print>>erf, 'Thread: %s' % threading.currentThread().getName()
            print>>erf, 'Client Address: ', client_address
            print>>erf, 'Request: ', repr(request)
            traceback.print_exc(file=erf)
            print>>erf, '\n*** Unrecoverable, server exiting!'
            print>>erf, '-'*40
            os._exit(0)

#----------------- end class RPCServer -------------------- 
Example #2
Source File: rpc.py    From BinderFilter with MIT License 6 votes vote down vote up
def handle_error(self, request, client_address):
        """Override TCPServer method

        Error message goes to __stderr__.  No error message if exiting
        normally or socket raised EOF.  Other exceptions not handled in
        server code will cause os._exit.

        """
        try:
            raise
        except SystemExit:
            raise
        except:
            erf = sys.__stderr__
            print>>erf, '\n' + '-'*40
            print>>erf, 'Unhandled server exception!'
            print>>erf, 'Thread: %s' % threading.currentThread().getName()
            print>>erf, 'Client Address: ', client_address
            print>>erf, 'Request: ', repr(request)
            traceback.print_exc(file=erf)
            print>>erf, '\n*** Unrecoverable, server exiting!'
            print>>erf, '-'*40
            os._exit(0)

#----------------- end class RPCServer -------------------- 
Example #3
Source File: __init__.py    From OTMql4AMQP with GNU Lesser General Public License v3.0 6 votes vote down vote up
def vPyDeInit():
    global oTKINTER_ROOT, sSTDOUT_FD
    if sSTDOUT_FD:
        try:
            sys.stdout = sys.__stdout__
            sys.stderr = sys.__stderr__
            sName = sSTDOUT_FD.name
            # sShowInfo('vPyDeInit', "Closing %s" % (sName,))
            sSTDOUT_FD.write('INFO : vPyDeInit ' + "Closing outfile %s\n" % (sName,))
            # oLOG.shutdown()
            sSTDOUT_FD.flush()
            sSTDOUT_FD.close()
            sSTDOUT_FD = None
        except Exception as e:
            # You probably have not stdout so no point in logging it!
            print "Error closing %s\n%s" % (sSTDOUT_FD, str(e),)
            sys.exc_clear()

    if oTKINTER_ROOT:
        oTKINTER_ROOT.destroy()
        oTKINTER_ROOT = None

    sys.exc_clear() 
Example #4
Source File: PyShell.py    From oss-ftp with MIT License 6 votes vote down vote up
def idle_showwarning(
        message, category, filename, lineno, file=None, line=None):
    """Show Idle-format warning (after replacing warnings.showwarning).

    The differences are the formatter called, the file=None replacement,
    which can be None, the capture of the consequence AttributeError,
    and the output of a hard-coded prompt.
    """
    if file is None:
        file = warning_stream
    try:
        file.write(idle_formatwarning(
                message, category, filename, lineno, line=line))
        file.write(">>> ")
    except (AttributeError, IOError):
        pass  # if file (probably __stderr__) is invalid, skip warning. 
Example #5
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _rmtree(path):
        def _rmtree_inner(path):
            for name in os.listdir(path):
                fullname = os.path.join(path, name)
                try:
                    mode = os.lstat(fullname).st_mode
                except OSError as exc:
                    print("support.rmtree(): os.lstat(%r) failed with %s" % (fullname, exc),
                          file=sys.__stderr__)
                    mode = 0
                if stat.S_ISDIR(mode):
                    _waitfor(_rmtree_inner, fullname, waitall=True)
                    os.rmdir(fullname)
                else:
                    os.unlink(fullname)
        _waitfor(_rmtree_inner, path, waitall=True)
        _waitfor(os.rmdir, path) 
Example #6
Source File: test_faulthandler.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_is_enabled(self):
        orig_stderr = sys.stderr
        try:
            # regrtest may replace sys.stderr by io.StringIO object, but
            # faulthandler.enable() requires that sys.stderr has a fileno()
            # method
            sys.stderr = sys.__stderr__

            was_enabled = faulthandler.is_enabled()
            try:
                faulthandler.enable()
                self.assertTrue(faulthandler.is_enabled())
                faulthandler.disable()
                self.assertFalse(faulthandler.is_enabled())
            finally:
                if was_enabled:
                    faulthandler.enable()
                else:
                    faulthandler.disable()
        finally:
            sys.stderr = orig_stderr 
Example #7
Source File: managers.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def serve_forever(self):
        '''
        Run the server forever
        '''
        self.stop_event = threading.Event()
        process.current_process()._manager_server = self
        try:
            accepter = threading.Thread(target=self.accepter)
            accepter.daemon = True
            accepter.start()
            try:
                while not self.stop_event.is_set():
                    self.stop_event.wait(1)
            except (KeyboardInterrupt, SystemExit):
                pass
        finally:
            if sys.stdout != sys.__stdout__:
                util.debug('resetting stdout, stderr')
                sys.stdout = sys.__stdout__
                sys.stderr = sys.__stderr__
            sys.exit(0) 
Example #8
Source File: rpc.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def handle_error(self, request, client_address):
        """Override TCPServer method

        Error message goes to __stderr__.  No error message if exiting
        normally or socket raised EOF.  Other exceptions not handled in
        server code will cause os._exit.

        """
        try:
            raise
        except SystemExit:
            raise
        except:
            erf = sys.__stderr__
            print('\n' + '-'*40, file=erf)
            print('Unhandled server exception!', file=erf)
            print('Thread: %s' % threading.current_thread().name, file=erf)
            print('Client Address: ', client_address, file=erf)
            print('Request: ', repr(request), file=erf)
            traceback.print_exc(file=erf)
            print('\n*** Unrecoverable, server exiting!', file=erf)
            print('-'*40, file=erf)
            os._exit(0)

#----------------- end class RPCServer -------------------- 
Example #9
Source File: run.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def manage_socket(address):
    for i in range(3):
        time.sleep(i)
        try:
            server = MyRPCServer(address, MyHandler)
            break
        except OSError as err:
            print("IDLE Subprocess: OSError: " + err.args[1] +
                  ", retrying....", file=sys.__stderr__)
            socket_error = err
    else:
        print("IDLE Subprocess: Connection to "
              "IDLE GUI failed, exiting.", file=sys.__stderr__)
        show_socket_error(socket_error, address)
        global exit_now
        exit_now = True
        return
    server.handle_request() # A single request only 
Example #10
Source File: crashsignal.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def destroy_crashlogfile(self):
        """Clean up the crash log file and delete it."""
        if self._crash_log_file is None:
            return
        # We use sys.__stderr__ instead of sys.stderr here so this will still
        # work when sys.stderr got replaced, e.g. by "Python Tools for Visual
        # Studio".
        if sys.__stderr__ is not None:
            faulthandler.enable(sys.__stderr__)
        else:
            faulthandler.disable()  # type: ignore[unreachable]
        try:
            self._crash_log_file.close()
            os.remove(self._crash_log_file.name)
        except OSError:
            log.destroy.exception("Could not remove crash log!") 
Example #11
Source File: run.py    From oss-ftp with MIT License 6 votes vote down vote up
def manage_socket(address):
    for i in range(3):
        time.sleep(i)
        try:
            server = MyRPCServer(address, MyHandler)
            break
        except socket.error as err:
            print>>sys.__stderr__,"IDLE Subprocess: socket error: "\
                                        + err.args[1] + ", retrying...."
    else:
        print>>sys.__stderr__, "IDLE Subprocess: Connection to "\
                               "IDLE GUI failed, exiting."
        show_socket_error(err, address)
        global exit_now
        exit_now = True
        return
    server.handle_request() # A single request only 
Example #12
Source File: ansitowin32.py    From pex with Apache License 2.0 5 votes vote down vote up
def isatty(self):
        stream = self.__wrapped
        if 'PYCHARM_HOSTED' in os.environ:
            if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
                return True
        try:
            stream_isatty = stream.isatty
        except AttributeError:
            return False
        else:
            return stream_isatty() 
Example #13
Source File: __init__.py    From OTMql4AMQP with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test():
    # changing sys.stdout can't be done under doctest
    if os.path.isfile('test.txt'): os.remove('test.txt')

    vPyInit('test.txt')
    assert os.path.isfile('test.txt'), "File not found: 'test.txt'"

    assert sys.stdout != sys.__stdout__
    assert sys.stderr != sys.__stderr__

    # This can't be done under doctest
    s = sPySafeEval('foobar')
    assert s.find('ERROR:') == 0
    assert s == "ERROR: name 'foobar' is not defined"

    vLog(0, "Level 0")
    vLog(1, "Level 1")
    vLog(2, "Level 2")
    vLog(3, "Level 3")
    vLog(4, "Level 4")

    # oLOG.root.setLevel(40)
    # oLOG.debug("NONONO oLOG.debug")
    # vLog(4, "NONO vLog 4")

    vPyDeInit()
    assert sys.stdout == sys.__stdout__
    assert sys.stderr == sys.__stderr__
    assert oTKINTER_ROOT is None
    assert sSTDOUT_FD is None

    # should check contents of test.txt
    oFd = open('test.txt', 'r')
    sContents = oFd.read()
    oFd.close()
    assert sContents.find("Level 4") > 0
    assert sContents.find("NONO") < 0 
Example #14
Source File: ws_client_ single_callback_L0.py    From CEX.IO-Client-Python3.5 with MIT License 5 votes vote down vote up
def _force_disconnect():
		while True:
			try:
				await asyncio.sleep(random.randrange(24, 64))
				print('test > Force disconnect')
				await client.ws.close()
			except Exception as ex:
				print("Exception at exit: {}".format(ex), sys.__stderr__) 
Example #15
Source File: PyShell.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def poll_subprocess(self):
        clt = self.rpcclt
        if clt is None:
            return
        try:
            response = clt.pollresponse(self.active_seq, wait=0.05)
        except (EOFError, OSError, KeyboardInterrupt):
            # lost connection or subprocess terminated itself, restart
            # [the KBI is from rpc.SocketIO.handle_EOF()]
            if self.tkconsole.closing:
                return
            response = None
            self.restart_subprocess()
        if response:
            self.tkconsole.resetoutput()
            self.active_seq = None
            how, what = response
            console = self.tkconsole.console
            if how == "OK":
                if what is not None:
                    print(repr(what), file=console)
            elif how == "EXCEPTION":
                if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
                    self.remote_stack_viewer()
            elif how == "ERROR":
                errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n"
                print(errmsg, what, file=sys.__stderr__)
                print(errmsg, what, file=console)
            # we received a response to the currently active seq number:
            try:
                self.tkconsole.endexecuting()
            except AttributeError:  # shell may have closed
                pass
        # Reschedule myself
        if not self.tkconsole.closing:
            self._afterid = self.tkconsole.text.after(
                self.tkconsole.pollinterval, self.poll_subprocess) 
Example #16
Source File: rpc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def pollmessage(self, wait):
        packet = self.pollpacket(wait)
        if packet is None:
            return None
        try:
            message = pickle.loads(packet)
        except pickle.UnpicklingError:
            print("-----------------------", file=sys.__stderr__)
            print("cannot unpickle packet:", repr(packet), file=sys.__stderr__)
            traceback.print_stack(file=sys.__stderr__)
            print("-----------------------", file=sys.__stderr__)
            raise
        return message 
Example #17
Source File: rpc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def putmessage(self, message):
        self.debug("putmessage:%d:" % message[0])
        try:
            s = dumps(message)
        except pickle.PicklingError:
            print("Cannot pickle:", repr(message), file=sys.__stderr__)
            raise
        s = struct.pack("<i", len(s)) + s
        while len(s) > 0:
            try:
                r, w, x = select.select([], [self.sock], [])
                n = self.sock.send(s[:BUFSIZE])
            except (AttributeError, TypeError):
                raise OSError("socket no longer exists")
            s = s[n:] 
Example #18
Source File: rpc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def debug(self, *args):
        if not self.debugging:
            return
        s = self.location + " " + str(threading.current_thread().name)
        for a in args:
            s = s + " " + str(a)
        print(s, file=sys.__stderr__) 
Example #19
Source File: rpc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def accept(self):
        working_sock, address = self.listening_sock.accept()
        if self.debugging:
            print("****** Connection request from ", address, file=sys.__stderr__)
        if address[0] == LOCALHOST:
            SocketIO.__init__(self, working_sock)
        else:
            print("** Invalid host: ", address, file=sys.__stderr__)
            raise OSError 
Example #20
Source File: remote_shell.py    From pylane with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        """
        main run entrance
        """
        self.name = "pylane-shell-thread"
        try:
            self.sock.connect()
            self.handle()
        except SystemExit:
            pass
        except:
            traceback.print_exc(file=sys.__stderr__)
        finally:
            if self.sock:
                self.sock.close() 
Example #21
Source File: ansitowin32.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def isatty(self):
        stream = self.__wrapped
        if 'PYCHARM_HOSTED' in os.environ:
            if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
                return True
        try:
            stream_isatty = stream.isatty
        except AttributeError:
            return False
        else:
            return stream_isatty() 
Example #22
Source File: ops.py    From LapSRN-tensorflow with Apache License 2.0 5 votes vote down vote up
def enable_print():
    """Enable console output, ``suppress_stdout`` is recommended.

    Examples
    --------
    - see tl.ops.disable_print()
    """
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__


# class temporary_disable_print:
#     """Temporarily disable console output.
#
#     Examples
#     ---------
#     >>> print("You can see me")
#     >>> with tl.ops.temporary_disable_print() as t:
#     >>>     print("You can't see me")
#     >>> print("You can see me")
#     """
#     def __init__(self):
#         pass
#     def __enter__(self):
#         sys.stdout = None
#         sys.stderr = os.devnull
#     def __exit__(self, type, value, traceback):
#         sys.stdout = sys.__stdout__
#         sys.stderr = sys.__stderr__
#         return isinstance(value, TypeError) 
Example #23
Source File: rootkernel.py    From parliament2 with Apache License 2.0 5 votes vote down vote up
def Debug(msg):
     print('Kernel main: %r' % msg, file=sys.__stderr__) 
Example #24
Source File: ansitowin32.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def isatty(self):
        stream = self.__wrapped
        if 'PYCHARM_HOSTED' in os.environ:
            if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
                return True
        try:
            stream_isatty = stream.isatty
        except AttributeError:
            return False
        else:
            return stream_isatty() 
Example #25
Source File: ansitowin32.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def isatty(self):
        stream = self.__wrapped
        if 'PYCHARM_HOSTED' in os.environ:
            if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
                return True
        try:
            stream_isatty = stream.isatty
        except AttributeError:
            return False
        else:
            return stream_isatty() 
Example #26
Source File: rpc.py    From oss-ftp with MIT License 5 votes vote down vote up
def debug(self, *args):
        if not self.debugging:
            return
        s = self.location + " " + str(threading.currentThread().getName())
        for a in args:
            s = s + " " + str(a)
        print>>sys.__stderr__, s 
Example #27
Source File: rpc.py    From oss-ftp with MIT License 5 votes vote down vote up
def localcall(self, seq, request):
        self.debug("localcall:", request)
        try:
            how, (oid, methodname, args, kwargs) = request
        except TypeError:
            return ("ERROR", "Bad request format")
        if oid not in self.objtable:
            return ("ERROR", "Unknown object id: %r" % (oid,))
        obj = self.objtable[oid]
        if methodname == "__methods__":
            methods = {}
            _getmethods(obj, methods)
            return ("OK", methods)
        if methodname == "__attributes__":
            attributes = {}
            _getattributes(obj, attributes)
            return ("OK", attributes)
        if not hasattr(obj, methodname):
            return ("ERROR", "Unsupported method name: %r" % (methodname,))
        method = getattr(obj, methodname)
        try:
            if how == 'CALL':
                ret = method(*args, **kwargs)
                if isinstance(ret, RemoteObject):
                    ret = remoteref(ret)
                return ("OK", ret)
            elif how == 'QUEUE':
                request_queue.put((seq, (method, args, kwargs)))
                return("QUEUED", None)
            else:
                return ("ERROR", "Unsupported message type: %s" % how)
        except SystemExit:
            raise
        except socket.error:
            raise
        except:
            msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\
                  " Object: %s \n Method: %s \n Args: %s\n"
            print>>sys.__stderr__, msg % (oid, method, args)
            traceback.print_exc(file=sys.__stderr__)
            return ("EXCEPTION", None) 
Example #28
Source File: rpc.py    From oss-ftp with MIT License 5 votes vote down vote up
def pollmessage(self, wait):
        packet = self.pollpacket(wait)
        if packet is None:
            return None
        try:
            message = pickle.loads(packet)
        except pickle.UnpicklingError:
            print >>sys.__stderr__, "-----------------------"
            print >>sys.__stderr__, "cannot unpickle packet:", repr(packet)
            traceback.print_stack(file=sys.__stderr__)
            print >>sys.__stderr__, "-----------------------"
            raise
        return message 
Example #29
Source File: rpc.py    From oss-ftp with MIT License 5 votes vote down vote up
def accept(self):
        working_sock, address = self.listening_sock.accept()
        if self.debugging:
            print>>sys.__stderr__, "****** Connection request from ", address
        if address[0] == LOCALHOST:
            SocketIO.__init__(self, working_sock)
        else:
            print>>sys.__stderr__, "** Invalid host: ", address
            raise socket.error 
Example #30
Source File: run.py    From oss-ftp with MIT License 5 votes vote down vote up
def handle_error(self, request, client_address):
        """Override RPCServer method for IDLE

        Interrupt the MainThread and exit server if link is dropped.

        """
        global quitting
        try:
            raise
        except SystemExit:
            raise
        except EOFError:
            global exit_now
            exit_now = True
            thread.interrupt_main()
        except:
            erf = sys.__stderr__
            print>>erf, '\n' + '-'*40
            print>>erf, 'Unhandled server exception!'
            print>>erf, 'Thread: %s' % threading.currentThread().getName()
            print>>erf, 'Client Address: ', client_address
            print>>erf, 'Request: ', repr(request)
            traceback.print_exc(file=erf)
            print>>erf, '\n*** Unrecoverable, server exiting!'
            print>>erf, '-'*40
            quitting = True
            thread.interrupt_main()