def echo(self, message): servers = get_servers() if servers: for server in list(servers.keys()): conn = Proxy(servers[server]) conn.echo(message) else: print('Não há nenhum servidor ativo') sys.exit(0)
def client(self): """ Set up a Pyro4 client so that we can talk to the LibreOfficeServer """ if not self._client: self._client = Proxy( 'PYRO:openlp.libreofficeserver@localhost:4310') if not self._client._pyroConnection: self._client._pyroReconnect() return self._client
def console_interface(just_hungry: Pyro4.Proxy) -> None: print("Welcome to Just Hungry!") postcode = "" while not POSTCODE_REGEX.match(postcode): postcode = input("Enter postcode to begin.\n > ") while True: print("\nCommands:\n" + "\n".join([ "exit - Exit program", "order - Make order", "orders - View orders", "postcode - Change postcode" ])) command = input("Please enter a command.\n > ").lower() if command == "exit": break elif command == "order": while True: item_count_entry = input( "Enter number of items to be ordered.\n > ") if item_count_entry.isdigit(): item_count = int(item_count_entry) break items: List[str] = [] for i in range(item_count): while True: item = input("Input item #%s.\n > " % (i + 1)) if not item.isspace(): items.append(item.strip()) break outcome, comment = just_hungry.place_order(postcode, items) print(("Order %s successfully placed!" % comment) if outcome else ("Could not place order: %s" % comment)) elif command == "orders": orders, message = just_hungry.get_orders(postcode) if orders: print("Orders:\n" + "\n".join([ "#%d: %s" % (i + 1, ", ".join(orders[i])) for i in range(len(orders)) ])) else: print(message if message else "No orders on record.") elif command == "postcode": postcode = "" while not POSTCODE_REGEX.match(postcode): postcode = input("Enter postcode to begin.\n > ") elif command == "": pass else: print("Unrecognised command.")
def __enter__(self): receiver, transmitter = create_sync_pair() self._process = Process(target=SingletonHost._SingletonServer.server_main, args=(self._socket, transmitter, self._name + 'Server'), name=self._name) self._process.start() _log.debug('%s: waiting for server', self._name) uri = receiver.receive() self._instance = PyroProxy(uri) # Default serpent serializer does not trasmit a class self._instance._pyroSerializer = 'pickle' _log.debug('%s: obtained proxy at %s', self._name, uri) return self
class MacLOController(PresentationController, LogMixin): """ Class to control interactions with MacLO presentations on Mac OS X via Pyro4. It starts the Pyro4 nameserver, starts the LibreOfficeServer, and then controls MacLO via Pyro4. """ log.info('MacLOController loaded') def __init__(self, plugin): """ Initialise the class """ log.debug('Initialising') super(MacLOController, self).__init__(plugin, 'maclo', MacLODocument, 'Impress on macOS') self.supports = ['odp'] self.also_supports = ['ppt', 'pps', 'pptx', 'ppsx', 'pptm'] self.server_process = None self._client = None self._start_server() def _start_server(self): """ Start a LibreOfficeServer """ libreoffice_python = Path( '/Applications/LibreOffice.app/Contents/Resources/python') libreoffice_server = AppLocation.get_directory( AppLocation.PluginsDir).joinpath('presentations', 'lib', 'libreofficeserver.py') if libreoffice_python.exists(): self.server_process = Popen( [str(libreoffice_python), str(libreoffice_server)]) @property def client(self): """ Set up a Pyro4 client so that we can talk to the LibreOfficeServer """ if not self._client: self._client = Proxy( 'PYRO:openlp.libreofficeserver@localhost:4310') if not self._client._pyroConnection: self._client._pyroReconnect() return self._client def check_available(self): """ MacLO is able to run on this machine. """ log.debug('check_available') return macuno_available def start_process(self): """ Loads a running version of LibreOffice in the background. It is not displayed to the user but is available to the UNO interface when required. """ log.debug('Started automatically by the Pyro server') self.client.start_process() def kill(self): """ Called at system exit to clean up any running presentations. """ log.debug('Kill LibreOffice') self.client.shutdown() self.server_process.kill()
line = self.sensor_connection.readline() except ValueError: print("No Connection") def read_data(self): try: line = self.sensor_connection.readline() self.read_count += 1 except ValueError: print("No Connection") return line def read_and_process(self): return self.read_data().rstrip("\n\r") if __name__ == '__main__': sc = SensorController("1", "pos_proximity") sc.connect_to_sensor() sc.next_read() cs = Proxy("PYRONAME:CommunicationService") while True: sensor_input_data = sc.read_and_process() print(sensor_input_data) cs.set_value_sensor_queue(sensor_input_data) sleep(1)
from Pyro4 import locateNS, Proxy fr = Proxy(locateNS().lookup("frontend")) for _ in range(100): while True: try: fr.add_rating(1, '1', 0) break except RuntimeError: pass
def get_replica(): servers = get_servers() if servers: server_name = get_first_replica(servers) return Proxy(servers[server_name])
def line_task(server_uri, y): with Proxy(server_uri) as calcproxy: return calcproxy.calc_photoimage_line(y, res_x, res_y)
""" Example of using a server instance to access server methods The first example ignores the server's Pyro4Server superclass and creates a local instance. The result is returned. The second example assumes that the server is a normal Pyro4 server. It will accept a connection and allow a method to be invoked but no result is returned. """ from async_server import BasicServer srvr = BasicServer() print "instance returned:", srvr.square(2) from Pyro4 import Proxy uri = "PYRO:BasicServer@localhost:9091" proxy = Proxy(uri) print "proxy returned:", proxy.square(2)
class SingletonHost: _LOCAL_SINGLETONS_BY_NAME = {} _LOCAL_SINGLETONS_BY_ID = {} class _SingletonServer: def _instantiate(self, singleton_cls): try: instance = singleton_cls() except Exception as e: # pragma: no cover # This doesn't need to be covered by testing, we use it for debugging only _log.exception('Unable to instantiate %s.', singleton_cls.__name__) raise e id_name_pair = (id(instance), singleton_cls.__name__) self._hosted_singletons.append(id_name_pair) SingletonHost._LOCAL_SINGLETONS_BY_ID[id_name_pair[0]] = instance SingletonHost._LOCAL_SINGLETONS_BY_NAME[id_name_pair[1]] = instance # _log.info('Registered objects on {}: {}'.format(self._name, SingletonHost._LOCAL_SINGLETONS_BY_ID)) return instance def _clear_instantiated_objs(self): for instance_id, instance_name in self._hosted_singletons: del SingletonHost._LOCAL_SINGLETONS_BY_NAME[instance_name] del SingletonHost._LOCAL_SINGLETONS_BY_ID[instance_id] del self._hosted_singletons[:] @pyro_expose def register(self, singleton_cls): uri = self._daemon.register(self._instantiate(singleton_cls), singleton_cls.__name__) _log.debug('%s: serving at %s', self._name, uri) return str(uri) @pyro_expose @pyro_oneway def close(self): _log.debug('%s: will stop.', self._name) self._clear_instantiated_objs() # Need to run on another thread, or it will cause a ConnectionClosedError Thread(target=self._daemon.shutdown, name='shutdown_thread').start() def __init__(self, daemon, name=None): self._daemon = daemon self._name = self.__class__.__name__ if name is None else name self._hosted_singletons = [] @staticmethod def server_main(socket, transmit_sync, name='SingletonServer'): if os.path.exists(socket): # pragma: no cover os.remove(socket) daemon = PyroDaemon(unixsocket=socket) uri = daemon.register(SingletonHost._SingletonServer(daemon, name=name), name) _log.debug('%s: serving at %s', name, uri) transmit_sync.transmit(str(uri)) daemon.requestLoop() _log.debug('%s: stopped serving at %s', name, uri) @classmethod def local_singletons_by_name(cls): return cls._LOCAL_SINGLETONS_BY_NAME @classmethod def local_singletons_by_id(cls): return cls._LOCAL_SINGLETONS_BY_ID def __enter__(self): receiver, transmitter = create_sync_pair() self._process = Process(target=SingletonHost._SingletonServer.server_main, args=(self._socket, transmitter, self._name + 'Server'), name=self._name) self._process.start() _log.debug('%s: waiting for server', self._name) uri = receiver.receive() self._instance = PyroProxy(uri) # Default serpent serializer does not trasmit a class self._instance._pyroSerializer = 'pickle' _log.debug('%s: obtained proxy at %s', self._name, uri) return self def initiate_shutdown(self): if self._instance is not None: self._instance.close() _log.debug('%s: signalled exit', self._name) # On Linux, Pyro does not query the stopping flag unless we call something. self._instance = None def __exit__(self, exc_type, exc_val, exc_tb): self.initiate_shutdown() _log.debug('%s: waiting %0.1f seconds for server to join.', self._name, _SHUTDOWN_TIMEOUT) self._process.join(_SHUTDOWN_TIMEOUT) if self._process.is_alive(): # pragma: no cover _log.warning('%s: server did not join, terminating.', self._name) self._process.terminate() else: _log.debug('%s: server joined', self._name) self._process = None if os.path.exists(self._socket): os.remove(self._socket) def __call__(self, singleton_cls): if self._instance is None: # pragma: no cover raise RuntimeError('You must __enter__ into a %s.' % self.__class__.__name__) # We cannot send a custom class except through Pickle. We can't even pickle it and send the bytes through # serpent (at the best we could send them over with marshal). So let's just do pickle. We're trasmitting over # a local socket. if self._instance._pyroSerializer != 'pickle': # pragma: no cover raise RuntimeError('Cannot transmit classes to create through %s. Please use pickle' % str(self._instance._pyroSerializer)) return PyroProxy(self._instance.register(singleton_cls)) def __init__(self, socket, name=None): self._socket = socket self._process = None self._instance = None self._name = self.__class__.__name__ if name is None else name
import sys import random import time from Pyro4 import Proxy, locateNS r = Proxy(locateNS().lookup("replica:%s" % sys.argv[1])) t = {} for i in range(100): while True: try: t = r.update(('U', (1, 1, random.choice([0, 1]))), t) time.sleep(random.random() / 100) break except RuntimeError: pass
import pprint import sys from Pyro4 import Proxy, locateNS db = Proxy(locateNS().lookup("replica:%s" % sys.argv[1])).get_state()[1] # convert to JSON friendly output for movie in db["movies"].values(): movie["genres"] = list(sorted(movie["genres"])) for user_tags in db["tags"].values(): for user_id, tags in user_tags.items(): user_tags[user_id] = list(sorted(tags)) pprint.pprint(db, width=100)