Skip to content

Instantly share code, notes, and snippets.

@TTimo
Last active March 2, 2023 15:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TTimo/f5c69d1d3011eb2f6422af1ef9dca8cb to your computer and use it in GitHub Desktop.
Save TTimo/f5c69d1d3011eb2f6422af1ef9dca8cb to your computer and use it in GitHub Desktop.
Pyro4 + asyncio
#!/usr/bin/env python3
import select
import asyncio
import Pyro4
@Pyro4.expose
class GreetingMaker(object):
def get_fortune(self, name):
return "Hello, {0}. Here is your fortune message:\n" \
"Behold the warranty -- the bold print giveth and the fine print taketh away.".format(name)
daemon = Pyro4.Daemon()
uri = daemon.register(GreetingMaker)
ns = Pyro4.locateNS()
ns.register('example.greeting', uri)
async def main():
loop = asyncio.get_event_loop()
while True:
rs, _, _ = await loop.run_in_executor(
None,
select.select,
daemon.sockets, [], [], 3
)
if rs:
print('Daemon received a request')
daemon.events(rs)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
@graingert
Copy link

graingert commented Oct 19, 2021

you don't need an executor thread at all - you can use loop.add_reader:

#!/usr/bin/env python3

import select
import asyncio

import Pyro4


@Pyro4.expose
class GreetingMaker(object):
    def get_fortune(self, name):
        return "Hello, {0}. Here is your fortune message:\n" \
               "Behold the warranty -- the bold print giveth and the fine print taketh away.".format(name)



async def amain():
    loop = asyncio.get_running_loop()
    with Pyro4.Daemon() as daemon:
        uri = daemon.register(GreetingMaker)

        ns = Pyro4.locateNS()
        ns.register('example.greeting', uri)


        ready = []
        event = asyncio.Event()

        def callback(socket):
            ready.append(socket)
            event.set()

        old_sockets = set()
        while True:
            current_sockets = set(daemon.sockets)
            for socket in (old_sockets - current_sockets):
                loop.remove_reader(socket.fileno())

            for socket in (current_sockets - old_sockets):
                loop.add_reader(socket.fileno(), callback, socket)

            old_sockets = current_sockets

            await event.wait()
            event = asyncio.Event()
            daemon.events(ready)
            ready = []

    return 0


def main():
    return asyncio.run(main())


if __name__ == '__main__':
    sys.exit(main())

@TTimo
Copy link
Author

TTimo commented Oct 20, 2021

kudos to you I guess .. kinda mind blown that something I posted years ago is getting a response now .. I had to google what Pyro4 was

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment