pythonstdoutio-redirectionrpyc

Redirecting stdout for RPyC to local client without using Classic RPyC


How do I redirect stdout to my local client when using RPyC services? I know it is possible when using Classic RPyC by using

c = rpyc.classic.connect(ip)

c.modules.sys.stdout = sys.stdout

Does anyone have an equivalent code that I can use on my client side for a user-defined service like one below

class remoteServer(rpyc.Service):

    def on_connect(self):
        # code that runs when a connection is created
        # (to init the serivce, if needed)

        if not os.path.exists(self.LOG_DIRECTORY_PATH):
            os.mkdir(self.LOG_DIRECTORY_PATH);
            file = open(self.LOG_FILENAME, 'a');
        else:
            print 'Directory: ', self.LOG_DIRECTORY_PATH, 'already exists';

if __name__ == "__main__":
    server = ThreadedServer(remoteServer, port = 12345)
    server.start()

Solution

  • I'd do it with

    class RedirectingService(rpyc.Service):
        def exposed_redirect(self, stdout):
            sys.stdout = stdout
        def exposed_restore(self):
            sys.stdout = sys.__stdout__
    

    And then

    c = rpyc.connect("server", config={"allow_public_attrs":True})
    c.redirect(sys.stdout)
    ...
    c.restore()
    

    Have a look at http://rpyc.readthedocs.org/en/latest/api/core_protocol.html#rpyc.core.protocol.DEFAULT_CONFIG for the configuration options. The classic mode basically sets everything to True, which may be unsafe, but you can control what options you wish to set explicitly.