def run_main(func): from multiprocessing.connection import Client address, key = cPickle.loads(eintr_retry_call(sys.stdin.read)) with closing(Client(address, authkey=key)) as control_conn, closing(Client(address, authkey=key)) as data_conn: func(control_conn, data_conn)
#from multiprocessing.managers import BaseManager #class QueueManager(BaseManager): pass # #QueueManager.register('get_class') #m = QueueManager(address=(HOST, PORT), authkey=b'abc') #m.connect() #fun = m.get_class() # #print(fun('comm_connect',0)) from multiprocessing.connection import Client from array import array address = ('localhost', 6000) conn = Client(address, authkey=b'abc') print (conn.recv()) # => [2.25, None, 'junk', float]) print( conn.recv_bytes() ) # => 'hello' arr = array('i', [0, 0, 0, 0, 0]) #print (conn.recv_bytes_into(arr)) # => 8 print (arr ) # => array('i', [42, 1729, 0, 0, 0]) conn.close() #queue.put('hello') #print(kiwoom.aa())
def run_main(func): from multiprocessing.connection import Client from contextlib import closing address, key = cPickle.loads(eintr_retry_call(sys.stdin.read)) with closing(Client(address, authkey=key)) as conn: raise SystemExit(func(conn))
def __init__(self): config = crawler.read_config(crawler.PROJECT_CONFIG_PATH) server_port = crawler.analysis_config( config, "LISTENER_PORT", 0, crawler.CONFIG_ANALYSIS_MODE_INTEGER) self.conn = Client((portListenerEvent.SERVER_IP, server_port))
def main(): if iswindows: if '--multiprocessing-fork' in sys.argv: # We are using the multiprocessing module on windows to launch a # worker process from multiprocessing import freeze_support freeze_support() return 0 # Close open file descriptors inherited from parent # On Unix this is done by the subprocess module os.closerange(3, 256) if isosx and 'CALIBRE_WORKER_ADDRESS' not in os.environ and 'CALIBRE_SIMPLE_WORKER' not in os.environ and '--pipe-worker' not in sys.argv: # On some OS X computers launchd apparently tries to # launch the last run process from the bundle # so launch the gui as usual from calibre.gui2.main import main as gui_main return gui_main(['calibre']) csw = os.environ.get('CALIBRE_SIMPLE_WORKER', None) if csw: mod, _, func = csw.partition(':') mod = importlib.import_module(mod) func = getattr(mod, func) func() return if '--pipe-worker' in sys.argv: try: exec (sys.argv[-1]) except Exception: print('Failed to run pipe worker with command:', sys.argv[-1]) raise return address = msgpack_loads(unhexlify(os.environ['CALIBRE_WORKER_ADDRESS'])) key = unhexlify(os.environ['CALIBRE_WORKER_KEY']) resultf = unhexlify(os.environ['CALIBRE_WORKER_RESULT']).decode('utf-8') with closing(Client(address, authkey=key)) as conn: name, args, kwargs, desc = eintr_retry_call(conn.recv) if desc: prints(desc) sys.stdout.flush() func, notification = get_func(name) notifier = Progress(conn) if notification: kwargs[notification] = notifier notifier.start() result = func(*args, **kwargs) if result is not None and os.path.exists(os.path.dirname(resultf)): with lopen(resultf, 'wb') as f: f.write(pickle_dumps(result)) notifier.queue.put(None) try: sys.stdout.flush() except EnvironmentError: pass # Happens sometimes on OS X for GUI processes (EPIPE) try: sys.stderr.flush() except EnvironmentError: pass # Happens sometimes on OS X for GUI processes (EPIPE) return 0
def run(self, py_ubi_forge, file_id: Union[str, int], forge_file_name: str, datafile_id: int, options: Union[List[dict], None] = None): if options is not None: self._options = options # should do some validation here # TODO add select directory option save_folder = py_ubi_forge.CONFIG.get('dumpFolder', 'output') data = py_ubi_forge.temp_files(file_id, forge_file_name, datafile_id) if data is None: py_ubi_forge.log.warn(__name__, f"Failed to find file {file_id:016X}") return model_name = data.file_name if self._options[0]["Export Method"] == 'Wavefront (.obj)': model: mesh.BaseModel = py_ubi_forge.read_file(data.file) if model is not None: obj_handler = mesh.ObjMtl(py_ubi_forge, model_name, save_folder) obj_handler.export(model, model_name) obj_handler.save_and_close() py_ubi_forge.log.info(__name__, f'Exported {file_id:016X}') else: py_ubi_forge.log.warn(__name__, f'Failed to export {file_id:016X}') elif self._options[0]["Export Method"] == 'Collada (.dae)': obj_handler = mesh.Collada(py_ubi_forge, model_name, save_folder) obj_handler.export(file_id, forge_file_name, datafile_id) obj_handler.save_and_close() py_ubi_forge.log.info(__name__, f'Exported {file_id:016X}') elif self._options[0][ "Export Method"] == 'Send to Blender (experimental)': model: mesh.BaseModel = py_ubi_forge.read_file(data.file) if model is not None: c = Client(('localhost', 6163)) cols = [ Image.new('RGB', (1024, 1024), (128, 0, 0)) for _ in range(len(model.bones)) ] r = 5 for mesh_index, m in enumerate(model.meshes): c.send({ 'type': 'MESH', 'verts': tuple(tuple(vert) for vert in model.vertices), 'faces': tuple( tuple(face) for face in model.faces[mesh_index] [:m['face_count']]) }) for vtx in model.vert_table: x, y = vtx['vt'].astype(numpy.float) / 2 for index, bone_index in enumerate(vtx['bn']): if vtx['bw'][index] > 0: draw = ImageDraw.Draw(cols[bone_index]) draw.ellipse( (x - r, y - r, x + r, y + r), fill=(vtx['bw'][index], vtx['bw'][index], vtx['bw'][index])) for index, im in enumerate(cols): im.save(f'{save_folder}/{model_name}_{index}.png') print(f'saved {save_folder}/{model_name}_{index}.png') c.send({ 'type': 'BONES', 'bone_id': [bone.bone_id for bone in model.bones], 'mat': [bone.transformation_matrix for bone in model.bones], })
def setupConnection(): global conn conn = Client(('localhost', 6000), authkey='CHANGEKEY'.encode('utf-8'))
def _check_request_queue(self): if not self.in_shutdown: self._dequeue_lock = True start_playback = False if self.player_process: if not self.player_active(): self.player_mode = None # player exited; make new player process, at least for idle start_playback = True elif self.player_mode != 'media' and len(self.requestqueue): # player in idle mode; requests queued -- stop current # player self.stop_player() start_playback = True else: # no player loaded; make new player process, at least for idle start_playback = True playback_error = None if start_playback: address = self.shm['config']['control_socket_file'] if not len(self.requestqueue): # nothing queued to play; idle logging.info('request queue empty; idling') self.player_mode = 'idle' self.player_process = Popen( ['/usr/bin/python2', 'bin/play.py', self.stream_id]) else: # pop next request from queue logging.info('dequeing and playing next request') self.current_request = self.requestqueue.popleft() # refresh info in case our media url went stale if self.current_request.request_type == RequestTypes.SITE: age = time() - self.current_request.last_fetched if age > self.shm['config']['PlayerManager'][ 'site_media_info_max_age']: logging.warning('media info stale; updating') self.current_request.update_site_media_info() # send error message if request prep failed, otherwise play if self.current_request.error: logging.warning('request failed to update') playback_error = True else: dur_string = '~' if self.current_request.live_source: dur_string = 'LIVE' elif self.current_request.duration > 0: dur_string = '{:d}:{:02d}'.format( *self.get_min_sec( self.current_request.duration)) msg = '/me is now playing * **{}** (from '.format( self.current_request.title ) + '**{}**)* — {} — *for {}*'.format( self.current_request.source_site, dur_string, self.current_request.sender) self.fire(events.do_send_message(msg), self.parent.ichcapi.channel) self.player_mode = 'media' self.player_process = Popen([ '/usr/bin/python2', 'bin/play.py', self.stream_id, self.current_request.media_uri ]) if self.player_process: # loop until socket file created timeout = self.shm['config']['PlayerManager'][ 'player_state_change_timeout'] wait = self.shm['config']['PlayerManager'][ 'player_state_change_delay'] while timeout > 0: timeout -= 1 if path.exists(address): break sleep(wait) if timeout == 0: # see if player simply failed to start if not self.player_process.poll(): logging.critical( 'timed out waiting for player socket and ' 'player still alive') self.fire(events.do_shutdown(), self.parent.channel) else: logging.error('player failed to start') playback_error = True else: # send play command to new player process, via client self.player_client = Client(address, authkey='phoebe') try: self.player_client.send(['play']) except IOError: logging.error( "IO error encountered when attempting to send " "to player connection") logging.critical( 'failed to issue play command to player ' 'process') self.fire(events.do_shutdown(), self.parent.channel) if playback_error: msg = "/msg {} error trying to play ".format( self.current_request.sender ) + "your request — {}".format( self.current_request.error) self.fire(events.do_send_message(msg), self.parent.ichcapi.channel) self._dequeue_lock = False Timer( float(self.shm['config'] ['PlayerManager']['queue_check_interval']), events.do_check_request_queue(), self.channel).register(self)
def serve_client(conn, id, cuentas, rel_lastacp_dirl, contactos, m, lock): connected = True ver = True while connected: try: m = conn.recv() except (EOFError, IOError): print 'connection abruptly closed by client' connected = False print 'received message:', m, 'from', id try: if m[1] == "new_user": try: crearcuenta(m, cuentas, contactos) except IOError: print 'conexion cerrada (crear cuenta)' connected = False if m[1] == "go_online": try: online(conn, id, cuentas, rel_lastacp_dirl, contactos, m) except IOError: print 'conexion cerrada (online)' connected = False if m[1] == "chat": try: chat(conn, id, cuentas, contactos, m, lock) except IOError: print 'conexion cerrada (chat)' connected = False if m[1] == "add_contact": try: agregar(m, id, cuentas, contactos) except IOError: print 'conexion cerrada (add_contact)' connected = False if m[1] == "quit": connected = False ver = False offline(conn, id, cuentas, rel_lastacp_dirl, contactos, m) conn.close() print cuentas print buzon print rel_lastacp_dirl print contactos except TypeError: print 'connection abruptly closed by client' connected = False ver = True print id, 'connection closed' if ver: for client, info in cuentas.items(): if info[1] == 'Online': if info[2] == id: rel_lastacp_dirl.pop(id) inf = cuentas.get(client) cuentas[client] = inf[0], 'Offline' for client, info in cuentas.items(): if info[1] == 'Online': if not info[2] == id: if client in contactos.get(m[0][0]): conn = Client(address=info[3][0], authkey=info[3][1]) conn.send( ["server_notify_quit_user", m[0][0]]) conn.close()
def run(self): ''' This function overloads the Thread class function, and is called when you run start() to start a new thread. ''' try: #Setup dictionaries to convert between foqus and ALAMO #variable names. Also setup a list of input and output #variable names for ALAMO. I'm going to keep the dicts #for now in case using the FOQUS variables names in ALAMO #doesn't work out for some reason. uq_file = self.options[ "FOQUS Model (for UQ)"].value self.xList = self.input self.zList = self.output self.xi = {} self.zi = {} cn = self.graph.input.compoundNames(sort=True) for v in self.xList: self.xi[v] = cn.index(v) cn = self.graph.output.compoundNames(sort=False) for v in self.zList: self.zi[v] = cn.index(v) #Get options and show some information about settings adaptive = self.options['SAMPLER'].value alamoDir = self.alamoDir alamoDirFull = os.path.abspath(alamoDir) self.setupWorkingDir() adpexe = os.path.join(alamoDirFull, 'foqusALAMOClient.py') if os.path.isfile(adpexe): adpexe = win32api.GetShortPathName(adpexe) self.writeAlamoInputFile(adaptiveExe=adpexe) else: self.writeAlamoInputFile(adaptiveExe=adpexe) if self.checkNumVars(): return alamoExe = self.dat.foqusSettings.alamo_path alamoInput = self.options["Input File"].value alamoOutput = alamoInput.rsplit('.', 1)[0] + '.lst' self.msgQueue.put("------------------------------------") self.msgQueue.put("Starting ALAMO\n") self.msgQueue.put("Exec File Path: " + alamoExe) self.msgQueue.put("Sub-directory: " + alamoDir) self.msgQueue.put("Input File Name: " + alamoInput) self.msgQueue.put("Output File Name: " + alamoOutput) self.msgQueue.put("SAMPLER: " + str(adaptive)) self.msgQueue.put("UQ Driver File: " + uq_file) self.msgQueue.put("------------------------------------") # If using adaptive sampleing open a network socket to listen if adaptive: listener = listen.foqusListener(self.dat) listener.setInputs(self.input) listener.setOutputs(self.output) listener.failValue = self.options["PRESET"].value address = listener.address listener.start() #Run Alamo process = subprocess.Popen([ alamoExe, alamoInput], cwd=alamoDir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin = None, creationflags=win32process.CREATE_NO_WINDOW) line = process.stdout.readline() while process.poll() == None or line != b'': if line == b'': time.sleep(0.2) if line != b'': self.msgQueue.put(line.decode("utf-8").rstrip()) line = process.stdout.readline() if self.stop.isSet(): self.msgQueue.put("**terminated by user**") process.kill() break if adaptive: # stop the listener conn = Client(address) conn.send(['quit']) conn.close() alamoOutput = os.path.join(alamoDir, alamoOutput) if self.options['FUNFORM'].value != "Fortran": self.msgQueue.put("MUST USE FORTRAN FORM to make UQ and flowsheet plugins") self.msgQueue.put("Skipping plugin creation") return res = SurrogateParser.parseAlamo(alamoOutput) self.result = res #self.msgQueue.put(str(res)) self.writePlugin() SurrogateParser.writeAlamoDriver( self.result, uq_file, ii=self.ii, oi=self.oi, inputNames=self.xList2, outputNames=self.zList2) self.driverFile = uq_file except Exception: self.ex = sys.exc_info() logging.getLogger("foqus." + __name__).error( "Exception in ALAMO Thread", exc_info=sys.exc_info())
# -*- coding: utf-8 -*- """ Created on Thu Mar 31 10:47:49 2016 @author: alumno """ from multiprocessing.connection import Client print 'trying to connect' conn = Client(address=('147.96.18.19', 6000), authkey='secret password') print 'connection accepted' message = raw_input('Message to send? ') print 'sending message' conn.send(message) print 'received message', conn.recv() conn.close()
import time from rapidapi import str_rev_api, translate_api, weather_api, insta_api time.sleep(2) input_ports = { "instagram": 8001, "weather": 8002, "translate": 8003, "reverse": 8004, "C2C": 8005 } processor_port = int(sys.argv[1]) dispatcher_port = int(sys.argv[2]) listener = Listener(('localhost', processor_port), authkey=b'secret password') conn_2dp = Client(('localhost', dispatcher_port), authkey=b'secret password') running = True conn_2ia = listener.accept() print('in proc_mod connection accepted from', listener.last_accepted, processor_port) while running: msg = conn_2ia.recv() if msg == 'terminate': print(f"terminate processing module {processor_port}") conn_2dp.send('terminate') conn_2ia.close() running = False else: # print("data received for processing")
#!/usr/bin/env python2 from multiprocessing.connection import Client address = ('localhost', 6000) conn = Client(address, authkey='dp23y4fm') conn.send_bytes('stop') conn.close()
def getMaxPower(self): return self.maxPower def getStartupStatus(self): return self.startupStatus ## ## data = guiModel() ## Initializes the client, links to listener in presenter.py address = ('localhost', 6000) client = Client(address, authkey=None) ## ## Methods to set and send data object def setSpeed(speed): data.setSpeed(speed) resource.acquire() client.send(data) resource.release() def setBatteryLevel(batteryLevel): data.setBatteryLevel(batteryLevel) resource.acquire()
# ===================================== # Global setting # ===================================== folder_path = '/media/nvidia/Files/Centre/' resolution = (640, 480) record_FPS = 10 frequence = 1 / record_FPS FourCC = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D') port_num = 25002 # ===================================== # Network Configuration # ===================================== from multiprocessing.connection import Client client = Client(('localhost', port_num), authkey=b'peekaboo') # ===================================== # Camera setup # ===================================== import pyrealsense2 as rs pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.color, resolution[0], resolution[1], rs.format.bgr8, 30) pipeline.start(config) # ===================================== # Init value # =====================================
#!/usr/bin/env python # This script is an example for the 'fake-search-script' option # # This script is a companion to 'listener.py' and # should be run independently of RocketMap. # # See 'listener.py' for more details from multiprocessing.connection import Client import time from datetime import datetime, timedelta print('Waiting for connection...') connection = Client(('localhost', 7890)) print('...connected') latitude = 42.7 longitude = -84.5 count = 0 while True: time.sleep(3) fake_pokemon_objects = [{ 'pokemon_id': 132, # ditto 'disappear_time': (datetime.utcnow() + timedelta(seconds=15)), 'latitude': latitude, 'longitude': longitude + count * .0002
return check(i[0], i[1]) if __name__ == '__main__': filepath = None is_l = False is_m = False try: arg = sys.argv[1:] opts, args = getopt.getopt(sys.argv[1:], 'f:zt:k:sp', ['help', 'train']) for op, value in opts: if op == '-f': img = value elif op == '-k': k = int(value) elif op == '-p': my_id = int(value) c = Client('./server%d.temp' % my_id, authkey=b'lee123456') # 将信息传送给服务端 c.send(arg) # 等待服务端处理结果 ar = c.recv() is_Ok = False for i in ar: if i == 'Next': is_Ok = True elif is_Ok: is_Ok = False print(check(i[0], i[1])) except EOFError: print('Connection closed, Please Reset Server.')
from multiprocessing.connection import Client address = ('localhost', 6000) conn = Client(address, authkey=b'secret password') while True: msg = input("Enter target city no--> ") conn.send(msg) conn.close()
import random import pygame from multiprocessing.connection import Client pygame.font.init() font = pygame.font.SysFont('Arial', 15, False, False) size = (500, 500) screen = pygame.display.set_mode(size) w, h = pygame.display.get_surface().get_size() pygame.display.set_caption("SNAKE CLIENT") fps_obj = pygame.time.Clock() fps = 12 address = ('127.0.0.1', 6000) # conn = Client(address, authkey='secret password') conn = Client(address) GRIDSIZE = 20 NO_OF_GRIDS = (w - GRIDSIZE) / GRIDSIZE MOVE_RATE = 20 SIZE = 15 EXIT_GAME = False COLLIDED = False START = False BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (30, 200, 30) RED = (255, 0, 0) BLUE = (0, 100, 255)
ROLLING_EVENT.set() # start to roll out workers = [] GLOBAL_UPDATE_COUNTER = 0 GLOBAL_EP = 0 GLOBAL_POLICY_UPDATE_NUM = 0 GLOBAL_SAMPLE_SIZE = 0 GLOBAL_RUNNING_R = [] COORD = tf.train.Coordinator() QUEUE = queue.Queue() # workers putting data in this queue threads = [] for i in range(env_process): address_num = address_num_base * (i + 1) address = ('localhost', address_num) conn = Client(address, authkey=password_list[i]) worker = Worker(wid=i) workers.append(worker) t = threading.Thread(target=worker.work, args=(i, conn)) threads.append(t) send_connect_flag(conn) print('send connect flag to the env processing {}...'.format(i)) time.sleep(1) # add a PPO updating thread threads.append(threading.Thread(target=GLOBAL_PPO.update, )) print('start all worker threading...') for x in threads: x.start() print('all worker threading start success')
def __run(self): self.__conn = Client(('localhost', 60000), authkey=b'silenttrinity') self.run()
def send(self, flow_mod): conn = Client((self.address, self.port)) conn.send(json.dumps(flow_mod)) conn.close()
def AioClient(*args, **kwargs): """ Returns an AioConnection instance. """ conn = Client(*args, **kwargs) return AioConnection(conn)
# -*- coding: utf-8 -*- """ Created on Thu Mar 31 10:47:49 2016 @author: alumno """ from multiprocessing.connection import Client print 'trying to connect' conn = Client(address=('127.0.0.1', 6000), authkey='secret password') print 'connection accepted' answer = '' while answer != 'adios': message = raw_input('Message to send? ') print 'sending message' conn.send(message) answer = conn.recv() print 'received message', answer if answer == 'cerrando': break conn.close()
from multiprocessing.connection import Client c = Client(('localhost', 25000), authkey=b'peekaboo') c.send('hello') print('Got:', c.recv()) c.send(42) print('Got:', c.recv()) c.send([1, 2, 3, 4, 5]) print('Got:', c.recv())
#!/usr/bin/env python """ client.py """ from multiprocessing.connection import Client import sys address = ('localhost', 12345) conn = Client(address, authkey=b'pass') conn.send(sys.argv[1]) conn.close()
def enable_vendor_connection(self, address): self.vendor_address = address self.vendor_connection = Client(self.vendor_address) print("Vendor connection enabled.")
if line == "": continue _write(stdout, line) ''' example: announce route 1.2.3.4 next-hop 5.6.7.8 as-path [ 100 200 ] ''' #log.write(line + '\n') #log.flush() except: pass ''' main ''' if __name__ == '__main__': log = open(logfile, "w") conn = Client(('localhost', 6000), authkey='sdx') sender = Thread(target=_sender, args=(conn,sys.stdin,log)) sender.start() receiver = Thread(target=_receiver, args=(conn,sys.stdout,log)) receiver.start() sender.join() receiver.join() log.close()
def __init__(self, event_id: str, event_type): super().__init__(event_id, event_type) from multiprocessing.connection import Client address = ('localhost', 6000) self.conn = Client(address)
def run(): global connection connection = Client(('localhost', 6000), authkey=b'bluesky') bs.sim.doWork() connection.close() print('Node', nodeid, 'stopped.')