def main(): args = arg_parser() args = clean_dict(args) signal.signal(signal.SIGINT, signal_handler) methods = {'upload': "uploadapi", 'file-get-info': "file/getinfo", 'file-set-info': "file/setinfo", 'file-delete': "file/delete", 'file-move': "file/move", 'folder-get-info': "folder/getinfo", 'folder-set-info': "folder/setinfo", 'folder-delete': "folder/delete", 'folder-move': "folder/move", 'folder-create': "folder/create", 'folder-content': "folder/content"} token = None if 'username' in args: if 'password' not in args: args['password'] = getpass("Password? ") print("Logging in...") args['token'] = login(args['username'], args['password']) del args['password'] del args['username'] elif 'password' in args: del args['password'] result = None if args['action'] in methods: print("Starting...\n") args['action'] = methods[args['action']] if args['action'] == "uploadapi": result = upload(args) else: result = api_do(args) else: print("Action not recognized.") if result is not None: pretty_print(result)
def __init__(self): '''class constructor''' self.window = None self.tray_icon = None self.conversations = [] self.single_instance = None self.config = e3.common.Config() self.config_dir = e3.common.ConfigDir('emesene2') self.config_path = self.config_dir.join('config') self.config.load(self.config_path) if self.config.d_accounts is None: self.config.d_accounts = {} if self.config.d_remembers is None: self.config.d_remembers = {} self.session = None self.logged_in = False self.timeout_id = None self.cur_service = None self._parse_commandline() self._setup() signal.signal(signal.SIGINT, lambda *args: glib.idle_add(self.close_session())) signal.signal(signal.SIGTERM, lambda *args: glib.idle_add(self.close_session()))
def loop(self): if self.steps: end_time = self.logical_time + self.steps else: end_time = sys.maxint exit_code = 0 self.interrupted = False old_interrupt = None def interrupt(sgn, frame): msg.interactive("Interrupting fuzzer, dropping to console (press ^C again to terminate)") signal.signal(signal.SIGINT, self.old_interrupt) self.old_interrupt = None self.interrupted = True raise KeyboardInterrupt() self.old_interrupt = signal.signal(signal.SIGINT, interrupt) try: # Always connect to controllers explicitly self.simulation.connect_to_controllers() self._log_input_event(ConnectToControllers()) if self.delay_startup: # Wait until the first OpenFlow message is received log.info("Waiting until first OpenfFlow message received..") while self.simulation.god_scheduler.pending_receives() == []: self.simulation.io_master.select(self.delay) while self.logical_time < end_time: self.logical_time += 1 try: self.trigger_events() msg.event("Round %d completed." % self.logical_time) halt = self.maybe_check_invariant() if halt: exit_code = 5 break self.maybe_inject_trace_event() time.sleep(self.delay) except KeyboardInterrupt as e: if self.interrupted: interactive = Interactive(self.simulation_cfg, self._input_logger) interactive.simulate(self.simulation, bound_objects=( ('fuzzer', self), )) self.old_interrupt = signal.signal(signal.SIGINT, interrupt) else: raise e log.info("Terminating fuzzing after %d rounds" % self.logical_time) if self.print_buffers: self._print_buffers() finally: if self.old_interrupt: signal.signal(signal.SIGINT, self.old_interrupt) if self._input_logger is not None: self._input_logger.close(self, self.simulation_cfg) return exit_code
def save(model, timings, post_fix=""): print "Saving the model..." # ignore keyboard interrupt while saving start = time.time() s = signal.signal(signal.SIGINT, signal.SIG_IGN) model.save( model.state["save_dir"] + "/" + model.state["run_id"] + "_" + model.state["prefix"] + post_fix + "model.npz" ) cPickle.dump( model.state, open( model.state["save_dir"] + "/" + model.state["run_id"] + "_" + model.state["prefix"] + post_fix + "state.pkl", "w", ), ) numpy.savez( model.state["save_dir"] + "/" + model.state["run_id"] + "_" + model.state["prefix"] + post_fix + "timing.npz", **timings ) signal.signal(signal.SIGINT, s) print "Model saved, took {}".format(time.time() - start)
def register_signal(self, signum, callback): """callback signature: (signum)""" if signum not in self._signal_handlers: self._signal_handlers[signum] = [callback] signal.signal(signum, self._generic_signal_handler) else: self._signal_handlers[signum].append(callback)
def main_window(): """ Create main window from Glade UI file """ builder = Gtk.Builder() builder.add_from_file(dirname + '/data/ui/blivet-gui.ui') signal.signal(signal.SIGINT, signal.SIG_DFL) MainWindow = builder.get_object("MainWindow") MainWindow.connect("delete-event", Gtk.main_quit) dlist = ListDevices(builder) builder.get_object("disks_viewport").add(dlist.get_disks_view()) builder.get_object("partitions_viewport").add(dlist.return_partitions_view()) builder.get_object("actions_viewport").add(dlist.return_actions_view()) builder.get_object("image_window").add(dlist.return_partitions_image()) builder.get_object("vbox").add(dlist.get_partions_list().get_main_menu) builder.get_object("vbox").add(dlist.get_partions_list().get_toolbar) return MainWindow
def embeded_window(): """ Create Gtk.Plug widget """ window_id = 0 plug = Gtk.Plug(window_id) #FIXME print plug.get_id() builder = Gtk.Builder() builder.add_from_file(dirname + '/data/ui/blivet-gui.ui') signal.signal(signal.SIGINT, signal.SIG_DFL) vbox = builder.get_object("vbox") vbox.reparent(plug) dlist = ListDevices(builder) builder.get_object("disks_viewport").add(dlist.get_disks_view()) builder.get_object("partitions_viewport").add(dlist.return_partitions_view()) builder.get_object("actions_viewport").add(dlist.return_actions_view()) builder.get_object("image_window").add(dlist.return_partitions_image()) builder.get_object("vbox").add(dlist.get_partions_list().get_toolbar) return plug
def main(argv, __start): # __start is to time startup, it is a debugging tool! app = QtWidgets.QApplication(argv) # TODO: use python packaging facilities to get the path icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons", "logo-path.svg") icon = QtGui.QIcon(icon_path) app.setWindowIcon(icon) main_window = MainWindow() main_window.show() # Install SIGNINT handler. signal.signal(signal.SIGINT, lambda *args: QtWidgets.QApplication.quit()) # Let Python handle signals every 500 ms, so that for example # ctrl-c on the command line works. timer = QtCore.QTimer() timer.timeout.connect(lambda: None) # this just drops to python's # main thread timer.start(500) import time __stop = time.time() main_window.sb.set_tmp("Startup took {} s.".format(__stop - __start), timeout=20000) return app.exec_()
def daemonize( errfile ): """ Detach process and become a daemon. """ pid = os.fork() if pid: os._exit(0) os.setsid() signal.signal(signal.SIGHUP, signal.SIG_IGN) os.umask(0) pid = os.fork() if pid: os._exit(0) os.chdir("/") for fd in range(0,20): try: os.close(fd) except OSError: pass sys.stdin = open("/dev/null","r") sys.stdout = open("/dev/null","w") sys.stderr = ErrorLog( errfile )
def loop(self,worker_name=None): signal.signal(signal.SIGTERM, lambda signum, stack_frame: sys.exit(1)) try: self.start_heartbeats() while True and self.have_heartbeat: if self.worker_status[0] == DISABLED: logging.debug('Someone stopped me, sleeping until better times come (%s)' % self.worker_status[1]) self.sleep() continue logging.debug('looping...') task = self.pop_task() if task: self.empty_runs = 0 self.report_task(task,self.async(task)) else: self.empty_runs += 1 logging.debug('sleeping...') if self.max_empty_runs != 0: logging.debug('empty runs %s/%s', self.empty_runs, self.max_empty_runs) if self.empty_runs >= self.max_empty_runs: logging.info('empty runs limit reached, killing myself') self.die() self.sleep() except (KeyboardInterrupt, SystemExit): logging.info('catched') self.die()
def build(args): """ the entry point for all build subcommand tasks """ builder = None fail = False try: manifest = None with open(args.manifest, 'r') as fh: manifest = fh.read() buildspec = BuildSpec(manifest, args.version, args.type, args.parallel, args.projects) builder = BuilderFactory.create_builder(args.type, buildspec) def _signal_handler(*args): LOG.info("Process interrrupted. Cleaning up.") builder.cleanup() sys.exit() signal.signal(signal.SIGINT, _signal_handler) rc = builder.build() except Exception as e: LOG.exception("Oops something went wrong: %s", e) fail = True builder.cleanup() if fail: sys.exit(-1) sys.exit(rc)
def ignore_sigint(): """Ignore SIGINT for the duration.""" old_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) try: yield finally: signal.signal(signal.SIGINT, old_handler)
def serve_forever(self): """ Accepts connection from multiple clients. """ # register SIGTERM for graceful exit. def stop_gracefully(signum, frame): self.stop_server() signal.signal(signal.SIGINT, stop_gracefully) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(self.addr) log.debug('%s listening on %s' % (type(self).__name__, self.addr)) # start listening on this port sock.listen(5) # sock.setblocking(0) # spawn worker processes self.spawn_worker_processes() try: while True: # start accepting connections log.debug('Main: Waiting for incoming connections') connection, address = sock.accept() # connection.setblocking(0) serialized_socket = reduce_handle(connection.fileno()) self.conn_queue.put(serialized_socket) except socket.error: log.warning('Interrupt: Stopping main process') self.stop_server() finally: sock.close()
def main(): signal.signal(signal.SIGUSR1, DumpThreadStacks) parser = argparse.ArgumentParser() command_parsers = parser.add_subparsers(title='test types', dest='command') for test_type, config in sorted(VALID_COMMANDS.iteritems(), key=lambda x: x[0]): subparser = command_parsers.add_parser( test_type, usage='%(prog)s [options]', help=config.help_txt) config.add_options_func(subparser) args = parser.parse_args() try: return RunTestsCommand(args, parser) except base_error.BaseError as e: logging.exception('Error occurred.') if e.is_infra_error: return constants.INFRA_EXIT_CODE return constants.ERROR_EXIT_CODE except: # pylint: disable=W0702 logging.exception('Unrecognized error occurred.') return constants.ERROR_EXIT_CODE
def __init__(self, prompt="> ", stdin=None, stdout=None): if _debug: ConsoleCmd._debug("__init__") cmd.Cmd.__init__(self, stdin=stdin, stdout=stdout) Thread.__init__(self, name="ConsoleCmd") # check to see if this is running interactive self.interactive = sys.__stdin__.isatty() # save the prompt for interactive sessions, otherwise be quiet if self.interactive: self.prompt = prompt else: self.prompt = '' # gc counters self.type2count = {} self.type2all = {} # logging handlers self.handlers = {} # set a INT signal handler, ^C will only get sent to the # main thread and there's no way to break the readline # call initiated by this thread - sigh if hasattr(signal, 'SIGINT'): signal.signal(signal.SIGINT, console_interrupt) # start the thread self.start()
def main(): parser = argparse.ArgumentParser( description="xdot.py is an interactive viewer for graphs written in Graphviz's dot language.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=''' Shortcuts: Up, Down, Left, Right scroll PageUp, +, = zoom in PageDown, - zoom out R reload dot file F find Q quit P print Escape halt animation Ctrl-drag zoom in/out Shift-drag zooms an area ''' ) parser.add_argument( 'inputfile', metavar='file', nargs='?', help='input file to be viewed') parser.add_argument( '-f', '--filter', choices=['dot', 'neato', 'twopi', 'circo', 'fdp'], dest='filter', default='dot', metavar='FILTER', help='graphviz filter: dot, neato, twopi, circo, or fdp [default: %(default)s]') parser.add_argument( '-n', '--no-filter', action='store_const', const=None, dest='filter', help='assume input is already filtered into xdot format (use e.g. dot -Txdot)') parser.add_argument( '-g', '--geometry', action='store', dest='geometry', help='default window size in form WxH') options = parser.parse_args() inputfile = options.inputfile width = height = 512 if options.geometry: try: width, height = (int(i) for i in options.geometry.split('x')) except ValueError: parser.error('invalid window geometry') win = DotWindow(width=width, height=height) win.connect('delete-event', Gtk.main_quit) win.set_filter(options.filter) if inputfile and len(inputfile) >= 1: if inputfile == '-': win.set_dotcode(sys.stdin.read()) else: win.open_file(inputfile) if sys.platform != 'win32': # Reset KeyboardInterrupt SIGINT handler, so that glib loop can be stopped by it import signal signal.signal(signal.SIGINT, signal.SIG_DFL) Gtk.main()
def main(): # Instantiate the Infrared-Thermopile Sensor on I2C on bus 1 mySensor = TMP006.TMP006(1) ## Exit handlers ## # This stops python from printing a stacktrace when you hit control-C def SIGINTHandler(signum, frame): raise SystemExit # This lets you run code on exit, # including functions from mySensor def exitHandler(): print("Exiting") sys.exit(0) # Register exit handlers atexit.register(exitHandler) signal.signal(signal.SIGINT, SIGINTHandler) # activate periodic measurements mySensor.setActive(); # Print out temperature value and config-reg in hex every 0.5 seconds while(1): mySensor.getTemperature(True) hex(mySensor.getConfig()) time.sleep(.5)
def terminate(self): """ Terminate all the child processes of this ProcessManager, bringing the loop() to an end. """ if self._terminating: return False self._terminating = True print("sending SIGTERM to all processes", file=self.system_printer) for proc in self.processes: if proc.poll() is None: print("sending SIGTERM to pid {0:d}".format(proc.pid), file=self.system_printer) proc.terminate() def kill(signum, frame): # If anything is still alive, SIGKILL it for proc in self.processes: if proc.poll() is None: print("sending SIGKILL to pid {0:d}".format(proc.pid), file=self.system_printer) proc.kill() if ON_WINDOWS: # SIGALRM is not supported on Windows: just kill instead kill(None, None) else: # the default is POSIX signal.signal(signal.SIGALRM, kill) # @UndefinedVariable signal.alarm(5) # @UndefinedVariable
def rpc(self, method, *args, **kwargs): """ Send a command to the queue. Timeout after 10 seconds """ pubsub = self._redis.pubsub() channel = "%s%s" % (platform.node(), int(time.time())) pubsub.subscribe(channel) self._redis.rpush(RedisTransport.COMMAND_KEY, cPickle.dumps(RedisMessage(channel, method, args, kwargs))) resp = pubsub.listen() signal.signal(signal.SIGALRM, self.shutdown) signal.alarm(10) resp.next() # clear subscribe message response = resp.next() pubsub.unsubscribe() try: return cPickle.loads(response['data']) except: # pylint: disable=W0702 msg = "%s: Failed to receive response: %s" % \ (self.__class__.__name__, traceback.format_exc().splitlines()[-1]) self.logger.error(msg) return None
def main(): # Default subnet is required for the host tracker to work. subnet_control = SubnetControl() subnet_control.list() subnet_control.add_subnet("defaultSubnet", "10.0.0.254/8") raw_input("[Press enter when mininet is ready] ") print("-------------------------") # Add per-protocol flows so we can monitor stats that way x = analytics.add_protocol_flows() if (not x): print "Unable to add per-protocol flows" m = WaypointMonitor(Stats.TYPE_SUBNET, subnet="10.0.0.1/32") m.set_waypoint("10.0.0.2") m.set_large_flow_threshold(2000) # 2000 bytes m.start() # Register signal-handler to catch SIG_INT signal.signal(signal.SIGINT, signal_handler) signal.pause() # join() won't return until SIG_INT has been captured m.join()
def local(cmd, retry_ttl=0, retry_interval=3, capture=True, timeout=60, **kwargs): def retry(*args, **kwargs): log.info('failed cmd: {0}, ttl: {1}, sleep: {2}'.format( cmd, retry_ttl, retry_interval)) if retry_ttl > 0: time.sleep(retry_interval) local(cmd, retry_ttl - 1, retry_interval, capture) log_cmd = 'local> ' + cmd api.env.cmd_history.append(log_cmd) log.info(log_cmd) print_for_test(log_cmd) if api.env.is_test: result = test_cmd(cmd) else: signal.signal(signal.SIGALRM, retry) signal.alarm(timeout) try: result = api.local(cmd, capture=capture, **kwargs) finally: signal.alarm(0) result_msg = 'return> {0}'.format(result.return_code) log.info(result_msg) print_for_test(result_msg) return result
def __init__ (self,configuration): self.ip = environment.settings().tcp.bind self.port = environment.settings().tcp.port self.max_loop_time = environment.settings().reactor.speed self.half_loop_time = self.max_loop_time / 2 self.logger = Logger() self.daemon = Daemon(self) self.processes = None self.listener = None self.configuration = Configuration(configuration) self._peers = {} self._shutdown = False self._reload = False self._reload_processes = False self._restart = False self._route_update = False self._saved_pid = False self._commands = [] self._pending = [] signal.signal(signal.SIGTERM, self.sigterm) signal.signal(signal.SIGHUP, self.sighup) signal.signal(signal.SIGALRM, self.sigalrm) signal.signal(signal.SIGUSR1, self.sigusr1) signal.signal(signal.SIGUSR2, self.sigusr2)
def run(self): """Runs the handler, flushes the streams, and ends the request.""" # If there is a timeout if self._timeout: old_alarm = signal.signal(signal.SIGALRM, self.timeout_handler) signal.alarm(self._timeout) try: protocolStatus, appStatus = self.server.handler(self) except: traceback.print_exc(file=self.stderr) self.stderr.flush() if not self.stdout.dataWritten: self.server.error(self) protocolStatus, appStatus = FCGI_REQUEST_COMPLETE, 0 if __debug__: _debug(1, 'protocolStatus = %d, appStatus = %d' % (protocolStatus, appStatus)) # Restore old handler if timeout was given if self._timeout: signal.alarm(0) signal.signal(signal.SIGALRM, old_alarm) try: self._flush() self._end(appStatus, protocolStatus) except socket.error, e: if e[0] != errno.EPIPE: raise
def __init__(self, signum, handler_fn=None, wakeup=None): """Constructs a new SignalHandler instance. @type signum: int or list of ints @param signum: Single signal number or set of signal numbers @type handler_fn: callable @param handler_fn: Signal handling function """ assert handler_fn is None or callable(handler_fn) self.signum = set(signum) self.called = False self._handler_fn = handler_fn self._wakeup = wakeup self._previous = {} try: for signum in self.signum: # Setup handler prev_handler = signal.signal(signum, self._HandleSignal) try: self._previous[signum] = prev_handler except: # Restore previous handler signal.signal(signum, prev_handler) raise except: # Reset all handlers self.Reset() # Here we have a race condition: a handler may have already been called, # but there's not much we can do about it at this point. raise
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None): """Function for actually starting a paramiko tunnel, to be passed to multiprocessing.Process(target=this), and not called directly. """ username, server, port = _split_server(server) client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) try: client.connect(server, port, username=username, key_filename=keyfile, look_for_keys=True, password=password) # except paramiko.AuthenticationException: # if password is None: # password = getpass("%s@%s's password: "******"Port forwarding stopped uncleanly: %s"%e) sys.exit(255)
def main(argv): global command try: opts, args = getopt.getopt(argv, "sari:t:", ["sort", "rand", "rev", "item", "test"]) except getopt.GetoptError: err() a = ["sort", "rand", "rev"] i = 1 test = "100" for opt, arg in opts: if opt == "-u": err() elif opt in ("-s", "sort"): command = "sort" elif opt in ("-a", "random"): command = "rand" elif opt in ("-r", "reversed"): command = "rev" elif opt in ("-i", "item"): i = int(arg) elif opt in ("-t", "test"): test = arg else: err() atexit.register(exit, (test)) signal.signal(signal.SIGTERM,exit) run(i, test)
def _daemonize(self): if not self.config.NODETACH: # fork so the parent can exist if os.fork(): return -1 # deconnect from tty and create a new session os.setsid() # fork again so the parent, (the session group leader), can exit. # as a non-session group leader, we can never regain a controlling # terminal. if os.fork(): return -1 # move to the root to avoit mount pb os.chdir("/") # set paranoid umask os.umask(0o77) # write pid in a file f = open(self._pid_file, "w") f.write(str(os.getpid())) f.close() # close standard descriptors sys.stdin.close() sys.stdout.close() sys.stderr.close() # put signal handler signal.signal(signal.SIGTERM, self.signal_handler) signal.signal(signal.SIGHUP, self.signal_handler)
def _install_signal_handlers(self): """Installs signal handlers for handling SIGINT and SIGTERM gracefully. """ signal.signal(signal.SIGINT, self.request_stop) signal.signal(signal.SIGTERM, self.request_stop)
def remove_signal_handler(self, sig): """Remove a handler for a signal. UNIX only. Return True if a signal handler was removed, False if not. """ self._check_signal(sig) try: del self._signal_handlers[sig] except KeyError: return False if sig == signal.SIGINT: handler = signal.default_int_handler else: handler = signal.SIG_DFL try: signal.signal(sig, handler) except OSError as exc: if exc.errno == errno.EINVAL: raise RuntimeError('sig {} cannot be caught'.format(sig)) else: raise if not self._signal_handlers: try: signal.set_wakeup_fd(-1) except (ValueError, OSError) as exc: logger.info('set_wakeup_fd(-1) failed: %s', exc) return True
def wait_for_keyboard(self): """quit when press q or press ctrl-c, or exception from other threads""" try: while True: time.sleep(2) # 减少死锁概率 print("enter 'q' to quit, 'r' to reload, 'l' to list ports.") key = input().lower().strip() if key == 'q': break elif key == 'r': log.info('main: reload config.') self.start_threads_from_config() elif key == 'l': try: print('name, station_port, dispatch_port, control_port') for name, config in sorted(self.configs['entry'].items()): control_port = str(config['controlPort']) if 'controlPort' in config else None print('%s, %d, %d, %s' % (name, config['stationPort'], config['listenPort'], control_port)) except Exception as e: print('Error when list config: %s' % e) except KeyboardInterrupt: pass except (EOFError, OSError): # no input signal.signal(signal.SIGINT, self.exit_by_signal) signal.signal(signal.SIGTERM, self.exit_by_signal) while not self.is_interrupt: time.sleep(1)
def handler(signum, frame): if signum == 2: print(" -> not finished yet!") return try: websocket = CWebSocketClient(["ADA-GBP"], 60) websocket.start() message_count = 0 while True: if websocket: if ( message_count != websocket.message_count and websocket.tickers is not None ): cls() print("\nMessageCount =", "%i \n" % websocket.message_count) print(websocket.candles) message_count = websocket.message_count time.sleep(5) # output every 5 seconds, websocket is realtime # catches a keyboard break of app, exits gracefully except KeyboardInterrupt: signal.signal(signal.SIGINT, handler) print("\nPlease wait while threads complete gracefully.") websocket.close() sys.exit(0)
self.write( self.service_status( ).decode( ).replace( "\n", "<br>" ) ) def signal_handler( sig, frame ): logger.critical( " graceful exit ... " ) Sensor.save_state( ) GPIO.cleanup( ) sys.exit( 0 ) try: logger = logging.getLogger( 'Security Monitor' ) logger.setLevel( logging.INFO ) handler = logging.handlers.SysLogHandler( address = ( 'localhost', 514 ), facility = logging.handlers.SysLogHandler.LOG_DAEMON ) handler.setLevel( logging.INFO ) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter( formatter ) logger.addHandler( handler ) signal.signal( signal.SIGTERM, signal_handler ) Sensor.configure_probes( ) if __name__ == "__main__": app = MainHandler.make_app( ) app.listen( 8888 ) tornado.ioloop.PeriodicCallback( Sensor.poll_next_in_list, 100 ).start( ) tornado.ioloop.PeriodicCallback( Sensor.save_state, 900000 ).start( ) tornado.ioloop.IOLoop.current( ).start( ) finally: GPIO.cleanup( ) exit( 0 )
logging.info('Response: "' + str(response) + '"') else: logging.info('Unknown request: "' + msg['text'] + '" from ' + msg['from']) self.voice.send_sms(msg['from'], cm.sms.unknown_command_response) # update the playlist self.update_playlist() # Delete all messages now that we've processed them for msg in messages: msg.delete(1) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--playlist', default=cm.sms.playlist_path, help='filename with the song playlist, one song per line in the format: ' '<song name><tab><path to song>') parser.add_argument('--setup', default=False, help='use this option to setup the default ' 'configuration file for Google Voice') parser.add_argument('--log', default='INFO', help='Set the logging level. levels:INFO, DEBUG, WARNING, ERROR, CRITICAL') args = parser.parse_args() check_sms = Sms(args.setup) signal.signal(signal.SIGINT, lambda x, y: check_sms.cancel()) check_sms.start() signal.pause()
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import signal def alarm_received(n, stack): return signal.signal(signal.SIGALRM, alarm_received) signals_to_names = {} for n in dir(signal): if n.startswith('SIG') and not n.startswith('SIG_'): signals_to_names[getattr(signal, n)] = n for s, name in sorted(signals_to_names.items()): handler = signal.getsignal(s) if handler is signal.SIG_DFL: handler = 'SIG_DFL' elif handler is signal.SIG_IGN: handler = 'SIG_IGN' print '%-10s (%2d):' % (name, s), handler
def sigterm_handler(signal, frame): global status print('Terminating room') status = "terminating" requests.put("{}/{}".format( constant.MAESTRO_ADDR, constant.ROOM_PING_ENDPOINT, ), json={ "timestamp": int(time.time()), "status": status }) exit() signal.signal(signal.SIGTERM, sigterm_handler) signal.signal(signal.SIGINT, sigterm_handler) def ping(): while True: try: print("ping {}/{}".format(constant.MAESTRO_ADDR, constant.ROOM_PING_ENDPOINT)) print("status {}".format(status)) requests.put("{}/{}".format( constant.MAESTRO_ADDR, constant.ROOM_PING_ENDPOINT, ), json={ "timestamp": int(time.time()),
import signal print("content-type: text/html") print() password = "******" print("enter passwd") menu_pass = getpass.getpass("enter password") #print("enter password") def interupt(x,y): print(" \n thank you for using my tool") exit() signal.signal(2, interupt ) if password != menu_pass: print("please enter a valid password") else: choice = int(input("enter your choice")) if choice == 12: bucket_name = input("Enter name of bucket: ") output = sb.getstatusoutput('ansible-playbook --vault-password-file=secret ./final_playbooks/s3.yml --extra-vars "bucket_name =' + bucket_name + '"') if output[0] == 0: sp.say("bucket created and configured automatically") sp.runAndWait() print("bucket created and configured autommatically") else: sp.say("there is some problem please check your connectivity")
self.pub_states[self.cur_table_id].publish(json.dumps(obs)) else: obs = self.cur_state_data obs["x"] = self.x; obs["y"] = self.y self.pub_states[self.cur_table_id].publish(json.dumps(obs)) else: self.pub_states[self.cur_table_id].publish(json.dumps(self.cur_state_data)) self.hand_raises = {} self.unknown_tables_state.clear() self.success = False self.interrupted = False self.mutex.release() else: rate.sleep() def signal_handler(signal, frame): print("\nprogram exiting gracefully") sys.exit(0) if __name__ == '__main__': try: signal.signal(signal.SIGINT, signal_handler) robot = False human_input = False num_tables = 3 Sensor_Aggregator(robot, human_input, num_tables).publish() except rospy.ROSInterruptException: pass
gdb.attach(target, execute="verify_exploit") bof_payload = sf.BufferOverflow(arch=64) bof_payload.set_input_start(0x38) bof_payload.add_int32(0x24, 0xcaf3baee) payload = bof_payload.generate_payload() target.sendline(payload) # Exploit Verification starts here 15935728 def handler(signum, frame): raise Exception("Timed out") def check_verification_done(): while True: if os.path.exists("pwned") or os.path.exists("rip"): sys.exit(0) signal.signal(signal.SIGALRM, handler) signal.alarm(2) try: while True: check_verification_done() except Exception: print("Exploit timed out")
def start(jobs, request=None, fastfail=False): if not isinstance(jobs, int): raise TypeError('jobs must be of type int') elif jobs <= 0: raise ValueError('jobs must be greater than 0') events.on_jobs(jobs) # Determine requested files. if request is not None: requested = set() for path in map(os.path.realpath, request): if graph.has_file(path): requested.add(graph.get_file(path)) continue path = os.path.abspath(system.build(os.path.relpath(path))) if graph.has_file(path): requested.add(graph.get_file(path)) continue raise ValueError('Can not find target "{}"'.format(path)) elif defaults: requested = set() for task in defaults: requested.update(task.outputs) else: requested = {file for file in graph.paths.values() if file.producer} # All primaries must be calculated for record-cleaning and warning. for task in graph.tasks: task.calculate_primary() # Calculate tasks to do. Record must be loaded first. record.load() outdated = graph.all_outdated_tasks_for(requested) events.on_outdated(len(outdated)) for task in graph.tasks: # Only display warning if we will not rebuild it. if record.has_primary(task.primary) and task not in outdated: warnings = record.get_warnings(task.primary) if warnings is not None: log.warning('Warnings by {}:\n{}'.format(task, warnings)) # Skip everything if there are no outdated tasks. if not outdated: record.clean() record.save() return log.debug('Setup threads.') for identifier in range(jobs): Worker(identifier).start() added = set() current = set() for task in outdated: if not any(input.producer in outdated for input in task.inputs): added.add(task) todo.put(task) current.add(task) def handle(signal, frame): print('\r \r', end='', flush=True) done.put((STOP, None, None)) signal.signal(signal.SIGINT, handle) failed = set() while current: if misc.windows: # Signal handling does not work very well on Windows... while True: try: task, exc, deposits = done.get(timeout=0.1) break except queue.Empty: pass else: task, exc, deposits = done.get() if task is STOP: log.error('Aborting {} running tasks.'.format(len(current))) # TODO: Remove outputs? break current.remove(task) outdated.remove(task) if exc: failed.add(task) events.on_fail(task, exc) # TODO: Remove outputs? if fastfail: log.error('Aborting {} running tasks.'.format(len(current))) # TODO: Remove outputs? break continue events.on_done(task) # Put all tasks in queue that can and should be done. for output in task.outputs: for dependant in output.dependants: if (dependant in outdated and dependant not in added and all(input.producer not in outdated and input.producer not in failed for input in dependant.inputs)): added.add(dependant) todo.put(dependant) current.add(dependant) task.deposits = {graph.get_file(deposit) for deposit in deposits[0]} task.warnings = deposits[1] if task.warnings is not None: log.warning('Warnings by {}:\n{}'.format(task.primary, task.warnings)) task.calculate_secondary() record.update(task) record.clean() record.save()
# # RoboComp is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with RoboComp. If not, see <http://www.gnu.org/licenses/>. # import sys, traceback, Ice, IceStorm, subprocess, threading, time, Queue, os import hashlib # Ctrl+c handling import signal signal.signal(signal.SIGINT, signal.SIG_DFL) from PySide import QtGui, QtCore import subprocess from collections import namedtuple Execution = namedtuple('Execution', ['path', 'binary', 'arguments', 'yakuakeTabName']) class GenericWorker(QtCore.QObject): kill = QtCore.Signal() def __init__(self, mprx): super(GenericWorker, self).__init__()
def execute(self, emulator=None): """ _execute_ """ # Are we using emulators again? if emulator is not None: return emulator.emulate(self.step, self.job) logging.info("Steps.Executors.%s.execute called", self.__class__.__name__) overrides = {} if hasattr(self.step, 'override'): overrides = self.step.override.dictionary_() logging.info("Using the following overrides: %s ", overrides) # Find alternate stageout location self.altLFN = overrides.get('altLFN', None) self.failedPreviousStep = overrides.get('previousCmsRunFailure', False) logging.info("Step configuration is: %s", self.step) # Wait timeout for stageOut waitTime = overrides.get('waitTime', 3600 + (self.step.retryDelay * self.step.retryCount)) matchFiles = [ ".log$", # matches the scram, wmagent and cmsRun logs "FrameworkJobReport.xml", "Report.pkl", "^PSet.py$", "^PSet.pkl$", "_condor_std*", # condor wrapper logs at the pilot top level ] ignoredDirs = ['Utils', 'WMCore', 'WMSandbox'] # Okay, we need a stageOut Manager useNewStageOutCode = False if getattr(self.step, 'newStageout', False) or \ ('newStageOut' in overrides and overrides.get('newStageOut')): useNewStageOutCode = True if not useNewStageOutCode: # old style manager = StageOutMgr.StageOutMgr(**overrides) manager.numberOfRetries = self.step.retryCount manager.retryPauseTime = self.step.retryDelay else: # new style logging.info("LOGARCHIVE IS USING NEW STAGEOUT CODE") manager = WMCore.Storage.FileManager.StageOutMgr(retryPauseTime=self.step.retryDelay, numberOfRetries=self.step.retryCount, **overrides) # Now we need to find all the reports # The log search follows this structure: ~pilotArea/jobArea/WMTaskSpaceArea/StepsArea # Start looking at the pilot scratch area first, such that we find the condor logs # Then look at the job area in order to find the wmagentJob log # Finally, at the taskspace area to find the cmsRun/FWJR/PSet files pilotScratchDir = os.path.join(self.stepSpace.taskSpace.location, '../../') logFilesToArchive = self.findFilesInDirectory(pilotScratchDir, matchFiles, ignoredDirs) # What if it's empty? if len(logFilesToArchive) == 0: msg = "Couldn't find any log files in the job" logging.error(msg) return logFilesToArchive # Now that we've gone through all the steps, we have to tar it out tarName = 'logArchive.tar.gz' tarBallLocation = os.path.join(self.stepSpace.location, tarName) with tarfile.open(tarBallLocation, 'w:gz') as tarBall: for f in logFilesToArchive: tarBall.add(name=f, arcname=f.replace(self.stepSpace.taskSpace.location, '', 1).lstrip('/')) fileInfo = {'LFN': self.getLFN(tarName), 'PFN': tarBallLocation, 'PNN': None, 'GUID': None } signal.signal(signal.SIGALRM, alarmHandler) signal.alarm(waitTime) try: manager(fileInfo) self.report.addOutputModule(moduleName="logArchive") (adler32, cksum) = calculateChecksums(tarBallLocation) reportFile = {"lfn": fileInfo["LFN"], "pfn": fileInfo["PFN"], "location": fileInfo["PNN"], "module_label": "logArchive", "events": 0, "size": 0, "merged": False, "checksums": {'adler32': adler32, 'cksum': cksum}} self.report.addOutputFile(outputModule="logArchive", aFile=reportFile) except Alarm: msg = "Indefinite hang during stageOut of logArchive" logging.error(msg) self.report.addError(self.stepName, 60404, "LogArchiveTimeout", msg) self.saveReport() raise WMExecutionFailure(60404, "LogArchiveTimeout", msg) except WMException as ex: self.report.addError(self.stepName, 60307, "LogArchiveFailure", str(ex)) self.saveReport() raise ex except Exception as ex: self.report.addError(self.stepName, 60405, "LogArchiveFailure", str(ex)) self.saveReport() msg = "Failure in transferring logArchive tarball\n" logging.exception(msg) raise WMException("LogArchiveFailure", message=str(ex)) signal.alarm(0) signal.alarm(waitTime) self.sendLogToEOS(overrides, tarBallLocation, useNewStageOutCode) signal.alarm(0) return
def run(config_cls=ConfigBuilder, route_builder=None, **kwargs): received_signal = threading.Event() with build_config(os.path.join(repo_root, "config.json"), config_cls=config_cls, **kwargs) as config: global logger logger = config.logger set_logger(logger) # Configure the root logger to cover third-party libraries. logging.getLogger().setLevel(config.log_level) def handle_signal(signum, frame): logger.debug("Received signal %s. Shutting down.", signum) received_signal.set() bind_address = config["bind_address"] if kwargs.get("alias_file"): with open(kwargs["alias_file"], 'r') as alias_file: for line in alias_file: alias, doc_root = [x.strip() for x in line.split(',')] config["aliases"].append({ 'url-path': alias, 'local-dir': doc_root, }) if route_builder is None: route_builder = get_route_builder routes = route_builder(config.aliases, config).get_routes() if config["check_subdomains"]: check_subdomains(config, routes) stash_address = None if bind_address: stash_address = (config.server_host, get_port("")) logger.debug("Going to use port %d for stash" % stash_address[1]) with stash.StashServer(stash_address, authkey=str(uuid.uuid4())): servers = start(config, routes, **kwargs) signal.signal(signal.SIGTERM, handle_signal) signal.signal(signal.SIGINT, handle_signal) while (all(subproc.is_alive() for subproc in iter_procs(servers)) and not received_signal.is_set() and not kwargs["exit_after_start"]): for subproc in iter_procs(servers): subproc.join(1) failed_subproc = 0 for subproc in iter_procs(servers): if subproc.is_alive(): logger.info('Status of subprocess "%s": running' % subproc.name) else: if subproc.exitcode == 0: logger.info( 'Status of subprocess "%s": exited correctly' % subproc.name) else: logger.warning( 'Status of subprocess "%s": failed. Exit with non-zero status: %d' % (subproc.name, subproc.exitcode)) failed_subproc += 1 return failed_subproc
logging.root.addHandler(logging.StreamHandler(sys.stdout)) #set debug log on if required: if options.debug is not None: toggle_logging(logging.DEBUG) else: toggle_logging(logging.INFO) #register posix signals for debugging: if os.name=="posix": def sigusr1(*args): dump_frames() toggle_logging(logging.DEBUG) def sigusr2(*args): toggle_logging(logging.INFO) signal.signal(signal.SIGUSR1, sigusr1) signal.signal(signal.SIGUSR2, sigusr2) if mode in ("start", "upgrade", "shadow") and supports_server: nox() from xpra.scripts.server import run_server return run_server(parser, options, mode, script_file, args) elif mode in ("attach", "detach", "screenshot", "version", "info"): return run_client(parser, options, args, mode) elif mode == "stop" and supports_server: nox() return run_stop(parser, options, args) elif mode == "list" and supports_server: return run_list(parser, options, args) elif mode == "_proxy" and supports_server: nox()
def _signal_handle(): """ signal setup """ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def exit_handler(signal, frame): """ Ctrl+Cが押されたときにデバイスを初期状態に戻して終了する。 """ print("\nExit") spi.close() sys.exit(0) # # メインルーチン # # 終了時に処理するシグナルハンドラを準備 signal.signal(signal.SIGINT, exit_handler) # データ保管用のキューを用意 queue = deque() # ログファイルの用意 # tsvfile = open('data'+datetime.now().strftime("%Y%m%d_%H%M%S")+'.tsv', 'a') tsvfile = open('data.tsv', 'a') data_count = 0 while True: time.sleep(0.2) # 温度センサーを読む temp = ConvertTemp(ConvertVolts(ReadChannel(temp_channel), 4), 4)
def app_signal(signum, frame): print("\ngot signal %s, exiting" % {signal.SIGINT:"SIGINT", signal.SIGTERM:"SIGTERM"}.get(signum, signum)) signal.signal(signal.SIGINT, deadly_signal) signal.signal(signal.SIGTERM, deadly_signal) gobject.timeout_add(0, app.quit, 128 + signum, priority=gobject.PRIORITY_HIGH)
def password_decrypt(token: bytes, password: str) -> bytes: decoded = b64d(token) salt, iterations, token = decoded[:16], decoded[16:20], b64e(decoded[20:]) iterations = int.from_bytes(iterations, 'big') key = _derive_key(password.encode(), salt, iterations) return Fernet(key).decrypt(token) def handler(signal_received, frame): # If CTRL+C or SIGINT received, send CLOSE request to server in order to exit gracefully. print(Style.RESET_ALL + Style.BRIGHT + Fore.YELLOW + "See you soon!") try: s.send(bytes("CLOSE", encoding="utf8")) except: pass os._exit(0) signal(SIGINT, handler) # Enable signal handler while True: # Grab data grom GitHub section try: res = requests.get(ipfile, data = None) #Use request to grab data from raw github file if res.status_code == 200: #Check for response content = res.content.decode().splitlines() #Read content and split into lines pool_address = content[0] #Line 1 = pool address pool_port = content[1] #Line 2 = pool port try: # Try to connect s.connect((str(pool_address), int(pool_port))) s.settimeout(timeout) SERVER_VER = s.recv(3).decode() jsonapi = requests.get("https://raw.githubusercontent.com/revoxhere/duco-statistics/master/api.json", data = None) # Use request to grab data from raw github file if jsonapi.status_code == 200: # Check for reponse
def main(**kwargs: Any) -> None: """A simple test runner. This test runner is essentially equivalent to `unittest.main` from the standard library, but adds support for Tornado-style option parsing and log formatting. It is *not* necessary to use this `main` function to run tests using `AsyncTestCase`; these tests are self-contained and can run with any test runner. The easiest way to run a test is via the command line:: python -m tornado.testing tornado.test.web_test See the standard library ``unittest`` module for ways in which tests can be specified. Projects with many tests may wish to define a test script like ``tornado/test/runtests.py``. This script should define a method ``all()`` which returns a test suite and then call `tornado.testing.main()`. Note that even when a test script is used, the ``all()`` test suite may be overridden by naming a single test on the command line:: # Runs all tests python -m tornado.test.runtests # Runs one test python -m tornado.test.runtests tornado.test.web_test Additional keyword arguments passed through to ``unittest.main()``. For example, use ``tornado.testing.main(verbosity=2)`` to show many test details as they are run. See http://docs.python.org/library/unittest.html#unittest.main for full argument list. .. versionchanged:: 5.0 This function produces no output of its own; only that produced by the `unittest` module (previously it would add a PASS or FAIL log message). """ from tornado.options import define, options, parse_command_line define( "exception_on_interrupt", type=bool, default=True, help=("If true (default), ctrl-c raises a KeyboardInterrupt " "exception. This prints a stack trace but cannot interrupt " "certain operations. If false, the process is more reliably " "killed, but does not print a stack trace."), ) # support the same options as unittest's command-line interface define("verbose", type=bool) define("quiet", type=bool) define("failfast", type=bool) define("catch", type=bool) define("buffer", type=bool) argv = [sys.argv[0]] + parse_command_line(sys.argv) if not options.exception_on_interrupt: signal.signal(signal.SIGINT, signal.SIG_DFL) if options.verbose is not None: kwargs["verbosity"] = 2 if options.quiet is not None: kwargs["verbosity"] = 0 if options.failfast is not None: kwargs["failfast"] = True if options.catch is not None: kwargs["catchbreak"] = True if options.buffer is not None: kwargs["buffer"] = True if __name__ == "__main__" and len(argv) == 1: print("No tests specified", file=sys.stderr) sys.exit(1) # In order to be able to run tests by their fully-qualified name # on the command line without importing all tests here, # module must be set to None. Python 3.2's unittest.main ignores # defaultTest if no module is given (it tries to do its own # test discovery, which is incompatible with auto2to3), so don't # set module if we're not asking for a specific test. if len(argv) > 1: unittest.main(module=None, argv=argv, **kwargs) # type: ignore else: unittest.main(defaultTest="all", argv=argv, **kwargs)
model.save('/scratch/li.baol/checkpoint_v100_only/' + job_name + '_' + str(current_epoch) + '.h5') print('(SIGTERM) terminating the process') checkpoint_dict = {} with open('checkpoint.json', 'r') as fp: checkpoint_dict = json.load(fp) checkpoint_dict[job_name] = 1 json_file3 = json.dumps(checkpoint_dict) with open('checkpoint.json', 'w') as fp: fp.write(json_file3) sys.exit() signal.signal(signal.SIGTERM, terminateProcess) ################################################################################# logdir = '/scratch/li.baol/tsrbrd_log/job_runs/' + model_type + '/' + job_name tensorboard_callback = TensorBoard(log_dir=logdir) #, update_freq='batch') class PrintEpoch(keras.callbacks.Callback): def on_epoch_begin(self, epoch, logs=None): global current_epoch #remaining_epochs = epochs - epoch current_epoch = epoch print('current epoch ' + str(current_epoch)) global epoch_begin_time
import bitcoin.rpc import bitcoin from bitcoin import * from bitcoin.core import * from bitcoin.core.script import * from bitcoin.core.scripteval import * from bitcoin.wallet import * from random import randint import random import sys, os, time, termios, tty, hashlib, signal def terminate(arg1, arg2): print("[*]Shutdown...") sys.exit(1) signal.signal(signal.SIGPIPE, signal.SIG_DFL) signal.signal(signal.SIGINT, terminate) bitcoin.SelectParams("regtest") nodes = [] class Node(): def __init__(self, rpc_user, rpc_password, rpc_port): self.rpc_user = rpc_user self.rpc_password = rpc_password self.rpc_port = rpc_port def rpc_connect(self): try: self.connect = bitcoin.rpc.Proxy(service_url="http://{}:{}@127.0.0.1:{}".format( self.rpc_user, self.rpc_password, self.rpc_port)) return True
return ret, s def handleSigint(sig, frame): click.echo('\r' +\ Fore.RED + "[ " + Fore.CYAN +\ "-" +\ Fore.RED + " ] " +\ Style.RESET_ALL + Fore.GREEN + "--- ---" + " " + Style.RESET_ALL, nl = False) # Quit gracefully click.echo(Style.RESET_ALL) sys.exit(0) # Set handler signal.signal(signal.SIGINT, handleSigint) @click.group() def cli(): pass @cli.command() @click.option("--secret", "-s", help = 'The secret used to generate a one-time password') @click.option("--all", "-a", is_flag = True, help = 'Show information of all stored one-time passwords') @click.option("--copy", "-c", is_flag = True, help = 'Copy one-time password to clipboard') @click.argument("name", required = False) def show(name, secret, all, copy): show_.cli(name, secret, all, copy) @cli.command() @click.option("--email", "-e", help = 'The email address this one-time password belongs to')
def handle_sigterm(signal, frame): # Since we want to terminate worker threads with prejudice, # we use os._exit, which directly terminates the process. # otherwise the worker try/catch will also catch the SystemExit logging.shutdown() os._exit(-1) def handle_sigusr1(signal, frame): for c in get_stack_dump(): log.info(c) # Dump all the stacks in case of CTRL-C signal.signal(signal.SIGINT, handle_sigint) # Also dump on sigterm signal.signal(signal.SIGTERM, handle_sigterm) # Also dump on sigusr1, but do not terminate signal.signal(signal.SIGUSR1, handle_sigusr1) def execute_command(cmd, ignore_errors=False, direct_io=False, cwd=None): ''' Execute the command `cmd` specified as a list of ['program', 'arg', ...] If ignore_errors is true, a non-zero exit code will be ignored, otherwise an exception is raised. If direct_io is True, do not capture the stdin and stdout of the command Returns the stdout of the command. ''' jcmd = " ".join(cmd)
file.close() def main(): resetLogfile() counter = 0 while (counter * logInterval) < examTime and not exit.is_set(): record(counter + 1) exit.wait(logInterval) counter = counter + 1 cleanupLogfile() def quit(signo, _frame): exit.set() if __name__ == '__main__': for sig in ('TERM', 'HUP', 'INT'): signal.signal(getattr(signal, 'SIG'+sig), quit) if(len(sys.argv) < 3): raise Exception("Too little arguments parsed") args = sys.argv try: examTime = int(args[1]) logInterval = int(args[2]) except: print("Wrong input format") main()
def main(mainParms): # Unpack incoming parameters # mainParms = {'startupDirectory': pwd, 'configFile': configFile, 'serialPort': args.serial, 'isDaemon':isDaemon, 'logFile':args.logfile } gConf = globalConfiguration() gConf.loadConfiguration(mainParms['configFile'], logFile=mainParms['logFile'], workingDir=mainParms['startupDirectory'], isDaemon=mainParms['isDaemon']) # Get logger logger = gConf.logger signalHandler = SignalHandler() mqtt.Client.connected_flag = False mqttClient = mqtt.Client(userdata={'logger': logger}) mqttClient.on_connect = mqtt_onConnect mqttClient.on_disconnect = mqtt_onDisconnect if gConf.configOpts['mqttUsername'] is not None and gConf.configOpts[ 'mqttPassword'] is not None: mqttClient.username_pw_set(username=gConf.configOpts['mqttUsername'], password=gConf.configOpts['mqttPassword']) # Initialization lastPacket = getMillis() - 1000.0 lastMQTTConnectAttempt = None logger.info("Starting run phase") signal.signal(signal.SIGINT, signalHandler.signalHandlerTerminate) signal.signal(signal.SIGTERM, signalHandler.signalHandlerTerminate) #signal.signal(signal.SIGKILL, signalHandler.signalHandler) # Main Run Loop - runs until something weird happens try: while True: if signalHandler.terminate: raise KeyboardInterrupt # Reconnect MQTT client if necessary if mqttClient.connected_flag is False and ( lastMQTTConnectAttempt is None or lastMQTTConnectAttempt + gConf.configOpts['mqttReconnectInterval'] < time.time()): # We don't have an MQTT client and need to try reconnecting try: lastMQTTConnectAttempt = time.time() mqttClient.loop_start() mqttClient.connect(gConf.configOpts['mqttBroker'], gConf.configOpts['mqttPort'], keepalive=60) while not mqttClient.connected_flag: time.sleep(0.01) # Wait for callback to fire mqttClient.loop_stop() except (KeyboardInterrupt): raise except: mqttClient.connected_flag = False try: # Start allowing MQTT callbacks mqttClient.loop_start() if mqttClient.connected_flag is False: logger.warning( "Skipping packet processing - no MQTT broker connected" ) continue updateTime = datetime.datetime.utcnow().replace( tzinfo=datetime.timezone.utc).isoformat() url = 'http://%s/current-sample' % ( gConf.configOpts['neurioAddress']) response = requests.get(url) data = response.json() # From the Neurio local API documentation # timestamp: Represents the UTC date/time value when measurement was executed in ISO8601 format. In case of an unsynchronized sensor time, this value is set to NOT_SYNCHRONIZED. # channels: Array containing information for [up to] the six logical channels. # cts: An array of 4 CTs. # # For channels the following applies: # type: Channel type in string format. Possible values are: PHASE_A_CONSUMPTION, PHASE_B_CONSUMPTION, PHASE_C_CONSUMPTION, NET, GENERATION, CONSUMPTION, SUBMETER. # ch: Channel number # eImp_Ws: Imported energy in watt-seconds # eExp_Ws: Exported energy in watt-seconds # p_W: Real power in watts # q_VAR: Reactive power in volt-amps reactive # v_V: Voltage in volts # label: User defined channel label. Only returned for SUBMETER type channels. # For cts the following applies: # ct: CT enumeration # p_W: Real power in watts # q_Var: Reactive power in volt-amps reactive # v_V: Voltage in volts # Things to send up: # Total V, WATTS, VAR # Phase V, I, W, VAR channels = {} for channel in data['channels']: name = channel['type'] number = channel['ch'] energy = channel['eImp_Ws'] p = channel['p_W'] q = channel['q_VAR'] v = channel['v_V'] pf = p / math.sqrt((p**2) + (q**2)) pf = math.cos(math.atan(q / p)) if name == 'PHASE_A_CONSUMPTION': name = 'phaseA' elif name == 'PHASE_B_CONSUMPTION': name = 'phaseB' else: name = None if name is not None: channels[name] = { 'number': number, 'energy': energy, 'real_power': p, 'reactive_power': q, 'volts': v, 'pf': pf } sensors = [ 'phaseA_voltage', 'phaseB_voltage', 'phaseA_power', 'phaseB_power', 'phaseA_pf', 'phaseB_pf', 'voltage', 'power' ] value = "0" units = 'unknown' topic = '' for sensor in sensors: if sensor == 'phaseA_voltage': value = "%.1f" % (channels['phaseA']['volts']) units = 'volts' elif sensor == 'phaseB_voltage': value = "%.1f" % (channels['phaseB']['volts']) units = 'volts' elif sensor == 'phaseA_power': value = "%d" % (channels['phaseA']['real_power']) units = 'watts' elif sensor == 'phaseB_power': value = "%d" % (channels['phaseB']['real_power']) units = 'watts' elif sensor == 'phaseA_pf': value = "%.2f" % (channels['phaseA']['pf']) units = 'none' elif sensor == 'phaseB_pf': value = "%.2f" % (channels['phaseB']['pf']) units = 'none' elif sensor == 'voltage': value = "%.1f" % (channels['phaseA']['volts'] + channels['phaseB']['volts']) units = 'volts' elif sensor == 'power': value = "%d" % (channels['phaseA']['real_power'] + channels['phaseB']['real_power']) units = 'watts' else: logging.error("Unknown sensor name [%s]" % (sensor)) try: topic = "%s/%s/%s" % (gConf.configOpts['locale'], gConf.configOpts['neurioName'], sensor) logging.debug("Publishing [%s] to topic [%s]" % (value, topic)) updateMessage = { 'type': 'update', 'value': value, 'units': units, 'time': updateTime, 'source': gConf.configOpts['sourceName'] } message = json.dumps(updateMessage, sort_keys=True) if mqttClient.connected_flag is True: mqttClient.publish(topic=topic, payload=message) except Exception as e: logger.exception("Failed to post update for [%s]" % (topic)) time.sleep(gConf.configOpts['postInterval']) except (KeyboardInterrupt): logger.warning("Caught KeyboardInterrupt, terminating") raise except Exception as e: logger.exception( "Caught some sort of exception, restarting the whole thing" ) exc_info = sys.exc_info() traceback.print_exception(*exc_info) del exc_info # Highest level, outer interrupt handler. except (KeyboardInterrupt): logger.info("User requested program termination, exiting...") try: if mqttClient is not None and mqttClient.connected_flag is True: mqttClient.disconnect() except: pass logger.info("Terminated") logging.shutdown()
def run_alter(self): signal.signal(signal.SIGINT, main_signal_handler) self.load_shard_locations() self.watcher = Watcher(self) self.watcher.daemon = True self.watcher.start() try: if len(self.settings.OPTIONS['filter_shards']) == 0 or ( len(self.settings.OPTIONS['filter_shards']) > 0 and self.settings.MODEL_SHARD_DB_CREDENTIALS['dbname'] in self.settings.OPTIONS['filter_shards']): mqueue = multiprocessing.Queue() mqueue.put({ 'shard': self.settings.MODEL_SHARD_DB_CREDENTIALS['dbname'], 'host': self.settings.MODEL_SHARD_DB_CREDENTIALS['host'], 'port': self.settings.MODEL_SHARD_DB_CREDENTIALS['port'], 'slave_host': self.settings.MODEL_SHARD_DB_CREDENTIALS['slave_host'], 'slave_port': self.settings.MODEL_SHARD_DB_CREDENTIALS['slave_port'] }) mqueue.put(None) # the temporary rewriting of the ignore_errors flag is so that when it gets copied to the process memory for the model shard worker, it will properly throw an error always tempignore = self.settings.OPTIONS['ignore_errors'] self.settings.OPTIONS['ignore_errors'] = False mworker = Worker( self, mqueue, self.settings.MODEL_SHARD_DB_CREDENTIALS['host'], self.settings.MODEL_SHARD_DB_CREDENTIALS['port'], 0, self.response_queue, None) mworker.start() self.settings.OPTIONS['ignore_errors'] = tempignore while mworker.is_alive(): mworker.join(1) if self.awaiting_shutdown: self.shutdown = True if len(self.errors) or len(self.unknownitems): print "Applying DDL to model shard failed, not continuing with remaining shards" self.shutdown_watcher() self.flush_queues() if len(self.errors): print "\n\nErrors received" for shard, e in self.errors.iteritems(): print "{0}: {1}".format(shard, str(e)) print "\n" return if self.settings.OPTIONS['running_mode'] == 'dry-run': print "Dry run completed successfully" self.shutdown_watcher() self.flush_queues() return for queue_key, queue in self.queues.iteritems(): self.threads[queue_key] = [] self.manager_queues[queue_key] = [] for worker_id in range(0, self.settings.OPTIONS['concurrency']): # put a marker job in the queue to stop this worker queue.put(None) host, port = queue_key.split(":") manager_queue = multiprocessing.Queue() worker = Worker(self, queue, host, port, worker_id, self.response_queue, manager_queue) self.threads[queue_key].append(worker) self.manager_queues[queue_key].append(manager_queue) worker.start() for g, threads in self.threads.iteritems(): for t in threads: while t.is_alive(): if self.awaiting_shutdown: self.shutdown_threads() t.join(.1) except Exception as e: print "Caught exception in main thread, exiting" self.flush_queues() self.shutdown_watcher() self.output_state() # set the shutdown flag so that any remaining threads exit self.shutdown = True
def __init__(self, mqtt_host='localhost', mqtt_port=1883): self.started = 0 self.stopped = 0 self.name = str(socket.gethostname()) # MQTT setup self.logger = logging.getLogger('MQTTBoard') self.logger.setLevel(logging.DEBUG) # self.ch = logging.StreamHandler() self.ch = logging.FileHandler('/var/log/LightsControl/lc.log') self.ch.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.ch.setFormatter(formatter) self.logger.addHandler(self.ch) self.mqtt_client = MQTTClient(self.name, mqtt_host, mqtt_port) self.logger.info("MQTT connecting to {0}:{1}".format( mqtt_host, mqtt_port)) self.mqtt_client.set_on_connect(self.mqtt_on_connect) self.mqtt_client.set_on_message(self.mqtt_on_message) self.mqtt_client.connect() self.logger.info("MQTT connected") self.mqtt_client.start() # GPIO setup GPIO.setmode(GPIO.BOARD) GPIO.setup(self.RELAY[1], GPIO.OUT) GPIO.output(self.RELAY[1], False) GPIO.setup(self.RELAY[2], GPIO.OUT) GPIO.output(self.RELAY[2], False) GPIO.setup(self.RELAY[3], GPIO.OUT) GPIO.output(self.RELAY[3], False) GPIO.setup(self.RELAY[4], GPIO.OUT) GPIO.output(self.RELAY[4], False) GPIO.setup(self.RELAY[5], GPIO.OUT) GPIO.output(self.RELAY[5], False) GPIO.setup(self.RELAY[6], GPIO.OUT) GPIO.output(self.RELAY[6], False) GPIO.setup(self.RELAY[7], GPIO.OUT) GPIO.output(self.RELAY[7], False) GPIO.setup(self.RELAY[8], GPIO.OUT) GPIO.output(self.RELAY[8], False) GPIO.setup(self.SENSOR[1], GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.SENSOR[2], GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.SENSOR[3], GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.SENSOR[4], GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.SENSOR[5], GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.SENSOR[6], GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.SENSOR[7], GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.SENSOR[8], GPIO.IN, pull_up_down=GPIO.PUD_UP) # Publish on MQTT self.base_topic = "homie" self.device_id = self.name.replace( ' ', '_') # Use name as device_id. Replacing spaces with underscore self.homie = "3.0.1" # self.localip = get_ip() # self.mac = get_mac() self.fw_name = "RaspiRelayboard" self.fw_version = "0.1" self.nodes = "" for i in range(1, 9): if i > 1: self.nodes += "," self.nodes += self.RELAY_NAME[i] for i in range(1, 9): self.nodes += "," self.nodes += self.SENSOR_NAME[i] self.implementation = "RaspberryPi" self.stats = "uptime,signal,cputemp,cpuload,freeheap,supply" self.stats_interval = 60 self.topic = "{0}/{1}".format(self.base_topic, self.device_id) self.logger.info("Using topic {0}".format(self.topic)) self.mqtt_publish_device() self.mqtt_send_stats() self.mqtt_send_nodes() self.started = 1 sleep(0.5) i = 1 while i <= 8: initial_power_topic = "{0}/{1}/power".format( self.topic, self.RELAY_NAME[i]) self.mqtt_client.publish(initial_power_topic, "false") i += 1 self.mqtt_client.publish(self.topic + "/$state", "ready") signal.signal(signal.SIGINT, self.handle_signal) self.read_switches() self.logger.info("Everything started and running.")
if '-c' in options: command = options['-c'] else: command = "sh" # Begin log with date/time in the form CCCCyymm.hhmmss fout.write ('# %4d%02d%02d.%02d%02d%02d \n' % time.localtime()[:-3]) ###################################################################### # Start the interactive session ###################################################################### p = pexpect.spawn(command) p.logfile = fout global global_pexpect_instance global_pexpect_instance = p signal.signal(signal.SIGWINCH, sigwinch_passthrough) print "Script recording started. Type ^] (ASCII 29) to escape from the script shell." p.interact(chr(29)) fout.close() return 0 def sigwinch_passthrough (sig, data): # Check for buggy platforms (see pexpect.setwinsize()). if 'TIOCGWINSZ' in dir(termios): TIOCGWINSZ = termios.TIOCGWINSZ else: TIOCGWINSZ = 1074295912 # assume s = struct.pack ("HHHH", 0, 0, 0, 0) a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s)) global global_pexpect_instance
def envoyer(params, fenetre): fenetre.destroy() fenetre2=Tk() fenetre2.protocol("WM_DELETE_WINDOW", lambda: intercepte(fenetre2)) fenetre2.resizable(width = False, height = False) fenetre2.iconbitmap("@../icone.xbm") h = fenetre2.winfo_screenheight() w = fenetre2.winfo_screenwidth() L, H = geoliste(fenetre2.geometry()) fenetre2.geometry("%dx%d+"%(L,H) + str(w/2-L/2) + "+" + str(h/2-H/2)) signal.signal(signal.SIGINT, signal_handler) print 'Press Ctrl+C pour arreter le client' for i in range(len(params), 255): params += " " try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.connect((osiris_ip, 6666)) s.sendall("ask ") print s.recv(29) if ("run" in params and valueGif.get() == 1): pass else: mbox('Les calculs sont prêts à être effectués.\nCliquez sur OK pour continuer.') s.sendall(params) s.settimeout(None) if "run" in params: received = receive_file(s, "mean-life-A.txt", 12) if received: received = receive_file(s,"mean-life-B.txt", 12, 3) if received: received = receive_file(s,"mean-A-in-A.txt", 12, 3) if received: received = receive_file(s,"mean-A-in-B.txt", 12, 3) if received: received = receive_file(s,"mean-B-in-A.txt", 12, 3) if received: received = receive_file(s,"mean-B-in-B.txt", 12, 3) if received: received = receive_file(s,"mean-C-in-A.txt", 12, 3) if received: received = receive_file(s,"mean-C-in-B.txt", 12, 3) if received: received = receive_file(s,"mean-A-out.txt", 12, 3) if received: received = receive_file(s,"mean-B-out.txt", 12, 3) if received: received = receive_file(s,"mean-C-out.txt", 12, 3) if received and int(params.split(" ")[8])>0: receive_gif(s, "Visualisation_simulation.gif") if received: os.system("Rscript Analyse.R") afficher(1, fenetre2) if valueGif.get() == 1: afficherGifRequete1() os.system("rm *.txt") global enregistrer if (valueGif.get() == 1): global enregistrer_gif if (not enregistrer_gif): os.system("rm Visualisation_simulation.gif") else: nom = "Visualisation_simulation.gif" eviter_double_enregistrement(nom, rep_gif, nom.index('.')) if rep_gif != os.getcwd(): os.system("rm -f Visualisation_simulation.gif") if (not enregistrer): os.system("rm Resultats_simulation.png") else: nom = "Resultats_simulation.png" eviter_double_enregistrement(nom, rep, nom.index('.')) if rep != os.getcwd(): os.system("rm -f Resultats_simulation.png") if "all" in params: fichier = open("results.txt", "w") i = 0 received = 1 while (received and i < 6): received = add_file(s, 12, fichier, i) i += 1 fichier.close() clean_file("results.txt") if (len(received)): os.system("Rscript phases.R") afficher(2, fenetre2) os.system("rm *.txt") if (not enregistrer): os.system("rm Diagramme_de_phase.png") else: nom = "Diagramme_de_phase.png" eviter_double_enregistrement(nom, rep, nom.index('.')) if (rep != os.getcwd()): os.system("rm -f Diagramme_de_phase.png") else: print "Fin de fichier non reçue..." print "dernière réception:", received if "explore" in params: compteur = 1; params = params.split(" ") Dmax = int(params[4]) Dstep = int(params[5]) Nessai = int(params[8]) nb_fichiers = 6*Dmax/Dstep*Nessai received = receive_file(s, s.recv(12).lstrip(), 12, 3) while (received and compteur < nb_fichiers - 1): received = receive_file(s, s.recv(12).lstrip(), 12, 3) compteur += 1 if (received): #creer les dossiers for i in range (0, Nessai): os.system("mkdir essai"+str(i+1)) #assembler les fichiers entre eux i = 1 j = 1 N = 1 while (i < nb_fichiers/6 + 1): assembler([i, i+5], j, N) i += 1 j += Dstep if (j > Dmax): j = 1 N += 1 os.system("rm *.txt") for D in range(1, 1+Dmax, Dstep): heatphases(D, Nessai, int(params[6]), int(params[7])) os.system("convert -delay 100 -loop 0 *.png phases-3D-logscale.gif") for i in range (0, Nessai): os.system("rm -rf essai"+str(i+1)) os.system("rm -f *.png") afficher(3, fenetre2) if (not enregistrer): os.system("rm *.gif") else: nom = "phases-3D-logscale.gif" eviter_double_enregistrement(nom, rep, nom.index('.')) if rep != os.getcwd(): os.system("rm *.gif") except socket.error, e: print "erreur dans l'appel a une methode de la classe socket : %s"%e sys.exit(1)
def __init__(self): self.shutdown = False signal.signal(signal.SIGINT, self.signal_cntrl_c) args = self.parse_commandline_arguments() self.init_logging(args.logfilename, args.verbose) logging.info("Connecting to server: %s", args.server) logging.info(" Device ID: %s", args.device_id) logging.info(" Control topic: %s/%s/control", args.username, args.device_id) logging.info(" Data topic: %s/%s/data", args.username, args.device_id) device = dashio.Device(args.device_type, args.device_id, args.device_name) dash_conn = dashio.DashConnection(args.username, args.password) dash_conn.add_device(device) self.tadevice_view = dashio.DeviceView("testAlarm", "Test Alarm") self.alarm_btn1 = dashio.Button("ALARM_BTN1") self.tadevice_view.add_control(self.alarm_btn1) self.alarm_btn1.title = "A1" self.alarm_btn1.btn_state = dashio.ButtonState.OFF self.alarm_btn1.icon_name = dashio.Icon.BELL self.alarm_btn1.on_color = dashio.Color.RED self.alarm_btn1.message_rx_event += self.alarm_btn1_handler device.add_control(self.alarm_btn1) self.alarm_btn2 = dashio.Button("ALARM_BTN2") self.alarm_btn2.title = "A2" self.alarm_btn2.btn_state = dashio.ButtonState.OFF self.alarm_btn2.icon_name = dashio.Icon.BELL self.alarm_btn2.on_color = dashio.Color.RED self.alarm_btn2.message_rx_event += self.alarm_btn2_handler device.add_control(self.alarm_btn2) self.tadevice_view.add_control(self.alarm_btn2) self.alarm_btn3 = dashio.Button("ALARM_BTN3") self.alarm_btn3.title = "A3" self.alarm_btn3.btn_state = dashio.ButtonState.OFF self.alarm_btn3.icon_name = dashio.Icon.BELL self.alarm_btn3.on_color = dashio.Color.RED self.alarm_btn3.message_rx_event += self.alarm_btn3_handler device.add_control(self.alarm_btn3) self.tadevice_view.add_control(self.alarm_btn3) self.alarm1_ctrl = dashio.Alarm("TestingAlarms1", "A plop form Alarm1", SoundName.PLOP) self.alarm2_ctrl = dashio.Alarm("TestingAlarms2", "Squeaky from Alarm2", SoundName.SQUEAKY) self.alarm3_ctrl = dashio.Alarm("TestingAlarms3", "Whoosh from Alarm3", SoundName.WHOOSH) device.add_control(self.alarm1_ctrl) device.add_control(self.alarm2_ctrl) device.add_control(self.alarm3_ctrl) self.tadevice_view.add_control(self.alarm1_ctrl) self.tadevice_view.add_control(self.alarm2_ctrl) self.tadevice_view.add_control(self.alarm3_ctrl) device.add_control(self.tadevice_view) while not self.shutdown: time.sleep(1) device.close()
def shell(): """Run the full speedtest.net test""" global SHUTDOWN_EVENT, SOURCE, SCHEME, DEBUG SHUTDOWN_EVENT = threading.Event() signal.signal(signal.SIGINT, ctrl_c) args = parse_args() # Print the version and exit if args.version: version() if args.csv_header: csv_header() if len(args.csv_delimiter) != 1: raise SystemExit('--csv-delimiter must be a single character') validate_optional_args(args) socket.setdefaulttimeout(args.timeout) # If specified bind to a specific IP address if args.source: SOURCE = args.source socket.socket = bound_socket if args.secure: SCHEME = 'https' debug = getattr(args, 'debug', False) if debug == 'SUPPRESSHELP': debug = False if debug: DEBUG = True # Pre-cache the user agent string build_user_agent() if args.simple or args.csv or args.json: quiet = True else: quiet = False # Don't set a callback if we are running quietly if quiet or debug: callback = do_nothing else: callback = print_dots printer('Retrieving speedtest.net configuration...', quiet) try: speedtest = Speedtest() except (ConfigRetrievalError, HTTP_ERRORS): printer('Cannot retrieve speedtest configuration') raise SpeedtestCLIError(get_exception()) if args.list: try: speedtest.get_servers() except (ServersRetrievalError, HTTP_ERRORS): print_('Cannot retrieve speedtest server list') raise SpeedtestCLIError(get_exception()) for _, servers in sorted(speedtest.servers.items()): for server in servers: line = ('%(id)5s) %(sponsor)s (%(name)s, %(country)s) ' '[%(d)0.2f km]' % server) try: print_(line) except IOError: e = get_exception() if e.errno != errno.EPIPE: raise sys.exit(0) # Set a filter of servers to retrieve servers = [] if args.server: servers.append(args.server) printer('Testing from %(isp)s (%(ip)s)...' % speedtest.config['client'], quiet) if not args.mini: printer('Retrieving speedtest.net server list...', quiet) try: speedtest.get_servers(servers) except NoMatchedServers: raise SpeedtestCLIError('No matched servers: %s' % args.server) except (ServersRetrievalError, HTTP_ERRORS): print_('Cannot retrieve speedtest server list') raise SpeedtestCLIError(get_exception()) except InvalidServerIDType: raise SpeedtestCLIError('%s is an invalid server type, must ' 'be an int' % args.server) printer('Selecting best server based on ping...', quiet) speedtest.get_best_server() elif args.mini: speedtest.get_best_server(speedtest.set_mini_server(args.mini)) results = speedtest.results printer( 'Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: ' '%(latency)s ms' % results.server, quiet) printer('Testing download speed', quiet, end=('', '\n')[bool(debug)]) speedtest.download(callback=callback) printer( 'Download: %0.2f M%s/s' % ((results.download / 1000.0 / 1000.0) / args.units[1], args.units[0]), quiet) printer('Testing upload speed', quiet, end=('', '\n')[bool(debug)]) speedtest.upload(callback=callback) printer( 'Upload: %0.2f M%s/s' % ((results.upload / 1000.0 / 1000.0) / args.units[1], args.units[0]), quiet) if args.simple: print_('Ping: %s ms\nDownload: %0.2f M%s/s\nUpload: %0.2f M%s/s' % (results.ping, (results.download / 1000.0 / 1000.0) / args.units[1], args.units[0], (results.upload / 1000.0 / 1000.0) / args.units[1], args.units[0])) elif args.csv: print_(results.csv(delimiter=args.csv_delimiter)) elif args.json: print_(results.json()) if args.share: printer('Share results: %s' % results.share(), quiet)