irmen / Pyro5

Pyro 5 - Python remote objects
https://pyro5.readthedocs.io
MIT License
303 stars 36 forks source link

Creating global variables client-side #73

Closed mxrch closed 1 year ago

mxrch commented 1 year ago

Hi ! Thanks for this awesome project.\ I was wondering how could I set global variables client-side and reusing them later ? They seem to disappear at each call :

Server :

image

Client :

image

Server's code :

from Pyro5.api import expose, serve

class CallbackServer(object):
    @expose
    def doCallback(self, callback):
        callback._pyroClaimOwnership()
        cmd = input("cmd : ")
        callback.execpy(cmd)
        return True

serve({
    CallbackServer: "example.callback2"
}, use_ns=False, host="localhost", port=27125)

Client's code :

import logging
import sys
import threading
from Pyro5.api import expose, callback, Daemon, Proxy

# initialize the logger so you can see what is happening with the callback exception message:
logging.basicConfig(stream=sys.stderr, format="[%(asctime)s,%(name)s,%(levelname)s] %(message)s")
log = logging.getLogger("Pyro5")
log.setLevel(logging.WARNING)

class CallbackHandler(object):
    @expose
    @callback
    def execpy(self, cmd):
        return exec(cmd)

class DaemonThread(threading.Thread):
    def __init__(self, callback_handler):
        self.callback_handler = callback_handler
        threading.Thread.__init__(self)
        self.daemon = True

    def run(self):
        with Daemon() as daemon:
            daemon.register(self.callback_handler)
            daemon.requestLoop()

callback_handler = CallbackHandler()
daemonthread = DaemonThread(callback_handler)
daemonthread.start()

with Proxy("PYRO:example.callback2@localhost:27125") as server:
    while True:
        server.doCallback(callback_handler)
irmen commented 1 year ago

Firstly be aware that what you're doing is scary stuff, it's not a good idea to execute random code that you receive over the network.

To answer your question, this is not a Pyro issue. It is likely due to the way you're calling exec. The default behavior is to execute the code in the local context. You can give extra arguments to exec to specify other scopes to run in. I suggest you try exec(cmd, globals(), locals()) instead.

irmen commented 1 year ago

Closing this now, feel free to reopen if further questions arise.