def _process_fifo_input(_thread_log, config_fifo): """ Pulls a command out of configuration FIFO and processes it into proper state and parameters :param _thread_log: console logger :param config_fifo: FIFO that transmits config commands to process :return: None """ line = config_fifo.readline()[:-1] state, params = _get_state_from_pipe_command(line) _thread_log.info( 'READ LINE toggle_memory_profile_via_fifo thread ====>{}, state: {}'. format(line, state.name)) if state == MemoryProfilerState.ON or state == MemoryProfilerState.OFF: set_memory_profile_logging(_thread_log, state.value.profiling_status) elif state == MemoryProfilerState.ECHO: _thread_log.info( 'ECHO MEMORY_PROFILE_LOGGING_ON ==> {}\nPYMPLER endpints: {}'. format(get_memory_profile_logging_on(), pympler_end_points)) elif state == MemoryProfilerState.PYMPLER and get_memory_profile_logging_on( ): _thread_log.info('Setting PYMPLER tracking for {} ==> {}'.format( params['endpoint'], params['persistence'])) _set_pympler_profiling_value(params['endpoint'], params['persistence']) elif state == MemoryProfilerState.CACHE: _publish_cache_size() elif state == MemoryProfilerState.DEBUG: _thread_log.info('---------- DEBUGGING PROCESS ({}) ----------'.format( os.getpid())) import rpdb rpdb.set_trace() _thread_log.info( '---------- DEBUGGING COMPLETED ({}) ----------'.format( os.getpid()))
def _set_breakpoint(self): """ Set a breakpoint for remote debugging Use the environment variable RDIFF_BACKUP_DEBUG to set a non-default listening address and/or port (default is 127.0.0.1:4444). Valid values are 'addr', 'addr:port' or ':port'. """ try: import rpdb debug_values = os.getenv("RDIFF_BACKUP_DEBUG", "").split(":") if debug_values != [""]: if debug_values[0]: debug_addr = debug_values[0] else: debug_addr = "127.0.0.1" if len(debug_values) > 1: debug_port = int(debug_values[1]) else: debug_port = 4444 rpdb.set_trace(addr=debug_addr, port=debug_port) else: # connect to the default 127.0.0.1:4444 rpdb.set_trace() except ImportError: log.Log("Remote debugging impossible, please install rpdb", log.Log.WARNING)
def start_prog(): pid = os.fork() if pid == 0: rpdb.set_trace() factor.factor_fibonacci(num=10) return pid
def onStart(self): # Debug debug = 0 if (Parameters["Mode1"] != "none"): Domoticz.Debugging(1) debug = 1 if (Parameters["Mode1"] == "ptvsd"): Domoticz.Log("Debugger ptvsd started, use 0.0.0.0:5678 to attach") import ptvsd # signal error on raspberry ptvsd.enable_attach() ptvsd.wait_for_attach() elif (Parameters["Mode1"] == "rpdb"): Domoticz.Log("Debugger rpdb started, use 'telnet 127.0.0.1 4444' on host to connect") import rpdb rpdb.set_trace() # signal error on raspberry # rpdb.handle_trap("0.0.0.0", 4444) # Heartbeat self.heartbeat = Heartbeat(int(Parameters["Mode2"])) self.heartbeat.setHeartbeat(self.UpdateStatus) # Create miio ip = Parameters["Address"] token = Parameters["Mode3"] self.miio = miio.airpurifier.AirPurifier(ip, token, 0, debug, True) Domoticz.Debug("Xiaomi AirPurifier created with address '" + ip + "' and token '" + token + "'") # Read function self.UpdateStatus(False) # Create devices for unit in self.__UNITS: field = unit["bindingStatusField"] value = getattr(self.status, field) if value is not None and unit["_Unit"] not in Devices: if "_Switchtype" in unit and unit["_Switchtype"] != None: Domoticz.Device( Name = unit["_Name"], Unit = unit["_Unit"], TypeName = unit["_TypeName"], Switchtype = unit["_Switchtype"], Image = unit["_Image"], Options = unit["_Options"]).Create() else: Domoticz.Device( Name = unit["_Name"], Unit = unit["_Unit"], TypeName = unit["_TypeName"], Options = unit["_Options"]).Create() # Read initial state self.UpdateStatus() DumpConfigToLog() return
def rpdb_view(request): """ rpdb solves that problem: it starts a server so you can just telnet into the interactive session you expected. """ import rpdb; rpdb.set_trace() return HttpResponse("This works.")
def _process_fifo_input(_thread_log, config_fifo): """ Pulls a command out of configuration FIFO and processes it into proper state and parameters :param _thread_log: console logger :param config_fifo: FIFO that transmits config commands to process :return: None """ line = config_fifo.readline()[:-1] state, params = _get_state_from_pipe_command(line) _thread_log.info('READ LINE toggle_memory_profile_via_fifo thread ====>{}, state: {}'.format(line, state.name)) if state == MemoryProfilerState.ON or state == MemoryProfilerState.OFF: set_memory_profile_logging(_thread_log, state.value.profiling_status) elif state == MemoryProfilerState.ECHO: _thread_log.info('ECHO MEMORY_PROFILE_LOGGING_ON ==> {}\nPYMPLER endpints: {}'.format( get_memory_profile_logging_on(), pympler_end_points)) elif state == MemoryProfilerState.PYMPLER and get_memory_profile_logging_on(): _thread_log.info('Setting PYMPLER tracking for {} ==> {}'.format(params['endpoint'], params['persistence'])) _set_pympler_profiling_value(params['endpoint'], params['persistence']) elif state == MemoryProfilerState.CACHE: _publish_cache_size() elif state == MemoryProfilerState.DEBUG: _thread_log.info('---------- DEBUGGING PROCESS ({}) ----------'.format(os.getpid())) import rpdb rpdb.set_trace() _thread_log.info('---------- DEBUGGING COMPLETED ({}) ----------'.format(os.getpid()))
def main(argv): def sigint_handler(signum, frame): print 'receive ctrl-c signal, will stop current test case running, and call cleanup function.' cleanup(test_case) sys.exit(1) if len(argv) == 0: raise Exception('No Test Case Path was provided to execute. The right command is: #testcase.py test_case_path') test_case_path = argv[0] sys.path.append(os.path.dirname(test_case_path)) test_case = imp.load_source('test_case', test_case_path) if not hasattr(test_case, 'test'): raise Exception('Not able to execute test case: %s, test case should at least define an entry function test()' % test_case_path) signal.signal(signal.SIGTERM, sigint_handler) try: ret = test_case.test() if ret == True or ret == None: sys.exit(0) else: cleanup(test_case) except Exception as e: if os.environ.get('WOODPECKER_START_DEBUGGER'): import rpdb rpdb.set_trace() traceback.print_exc(file=sys.stdout) cleanup(test_case)
def onStart(self): # Debug self.debug = 0 if (Parameters["Mode1"] != "none"): Domoticz.Debugging(1) self.debug = 1 if (Parameters["Mode1"] == 'ptvsd'): Domoticz.Log("Debugger ptvsd started, use 0.0.0.0:5678 to attach") import ptvsd # signal error on raspberry ptvsd.enable_attach() ptvsd.wait_for_attach() elif (Parameters["Mode1"] == 'rpdb'): Domoticz.Log("Debugger rpdb started, use 'telnet 127.0.0.1 4444' on host to connect") import rpdb rpdb.set_trace() # signal error on raspberry # rpdb.handle_trap("0.0.0.0", 4444) # Domoticz.Heartbeat(self.heartBeatFreq) self.repeatTime = int(Parameters["Mode2"]) self.remoteIP = Parameters["Address"] self.remotePort = Parameters["Port"] # Server Connection self.serverConn = Domoticz.Connection(Name="Data Connection", Transport="TCP/IP", Protocol="None", Port="9000") self.serverConn.Listen() # Client Connection if self.remoteIP: self.proxyConn = Domoticz.Connection(Name="Proxy Connection", Transport="TCP/IP", Protocol="None", Address=self.remoteIP, Port=self.remotePort) self.proxyConn.Connect()
def run(config, user_dir='/home/worker/output'): # Make the cutout subdirectory if it does not already exist. cutout_dir = os.path.join(user_dir, 'cutout') os.makedirs(cutout_dir, exist_ok=True) config['cutout_dir'] = cutout_dir # Configure logging formatter = logging.Formatter( "%(asctime)s %(name)8s %(levelname)5s %(message)s") fh = logging.FileHandler(config['metadata']['log']) fh.setLevel(logging.INFO) fh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) # Report to the JobHandler that the job has begun task_start(config) # Trigger debugging if activated and pause execution debug_loop = config['metadata']['debug'] if debug_loop: logger.info('Debugging is enabled. Invoking RPDB...') rpdb.set_trace() # Execute the primary task response = execute_task(config) # The `debug_loop` variable can be set to false using the interactive debugger to break the loop while debug_loop == True: response = execute_task(config) # Report to the JobHandler that the job is complete task_complete(config, response)
def main(argv): def sigint_handler(signum, frame): print 'receive ctrl-c signal, will stop current test case running, and call cleanup function.' cleanup(test_case) sys.exit(1) if len(argv) == 0: raise Exception( 'No Test Case Path was provided to execute. The right command is: #testcase.py test_case_path' ) test_case_path = argv[0] sys.path.append(os.path.dirname(test_case_path)) test_case = imp.load_source('test_case', test_case_path) if not hasattr(test_case, 'test'): raise Exception( 'Not able to execute test case: %s, test case should at least define an entry function test()' % test_case_path) signal.signal(signal.SIGTERM, sigint_handler) try: ret = test_case.test() if ret == True or ret == None: sys.exit(0) else: cleanup(test_case) except Exception as e: if os.environ.get('WOODPECKER_START_DEBUGGER'): import rpdb rpdb.set_trace() traceback.print_exc(file=sys.stdout) cleanup(test_case)
def main(): count = 0 while count < 10: rpdb.set_trace(long_living=True) print("here %d" % count) count += 1 print("done")
def doPost(self,request,response): rpdb.set_trace() # The debugger port by default is 4444 dw = DoWork() toClient = response.getWriter() response.setContentType ("text/html") toClient.println ("<html><head><title>Jython Servlet Test</title>" + "<body><h1>Servlet Jython Servlet at" + request.getContextPath() + "</h1>" + dw.sayHello() + "</body></html>")
def onStart(self): # Debug debug = 0 if (Parameters["Mode1"] != "none"): Domoticz.Debugging(1) debug = 1 if (Parameters["Mode1"] == "ptvsd"): Domoticz.Log("Debugger ptvsd started, use 0.0.0.0:5678 to attach") import ptvsd # signal error on raspberry ptvsd.enable_attach() ptvsd.wait_for_attach() elif (Parameters["Mode1"] == "rpdb"): Domoticz.Log( "Debugger rpdb started, use 'telnet 127.0.0.1 4444' on host to connect" ) import rpdb rpdb.set_trace() # signal error on raspberry # rpdb.handle_trap("0.0.0.0", 4444) # Heartbeat self.heartbeat = Heartbeat(int(Parameters["Mode2"])) self.heartbeat.setHeartbeat(self.UpdateStatus) # Create miio ip = Parameters["Address"] token = Parameters["Mode3"] self.miio = miio.airpurifier_miot.AirPurifierMiot( ip, token, 0, debug, True) Domoticz.Debug("Xiaomi AirPurifier created with address '" + ip + "' and token '" + token + "'") # Read function self.UpdateStatus(False) # Create devices if self.status != None: self.createDevices() self.devicesCreated = True # Read initial state self.UpdateStatus() DumpConfigToLog() return
def onStart(self): # Debug debug = 0 if (Parameters["Mode1"] != "none"): Domoticz.Debugging(1) debug = 1 if (Parameters["Mode1"] == "ptvsd"): Domoticz.Log("Debugger ptvsd started, use 0.0.0.0:5678 to attach") import ptvsd # signal error on raspberry ptvsd.enable_attach() ptvsd.wait_for_attach() elif (Parameters["Mode1"] == "rpdb"): Domoticz.Log( "Debugger rpdb started, use 'telnet 127.0.0.1 4444' on host to connect" ) import rpdb rpdb.set_trace() # signal error on raspberry # rpdb.handle_trap("0.0.0.0", 4444) # Heartbeat self.heartbeat = Heartbeat(int(Parameters["Mode2"])) self.heartbeat.setHeartbeat(self.UpdateStatus) # Create miio ip = Parameters["Address"] token = Parameters["Mode3"] self.miio = miio.philips_bulb.PhilipsBulb(ip, token, 0, debug, True) Domoticz.Debug("Xiaomi Miio Philips Bulb created with address '" + ip + "' and token '" + token + "'") # Create devices for unit in self.__UNITS: if unit["_Unit"] not in Devices: Domoticz.Device(Name=unit["_Name"], Unit=unit["_Unit"], TypeName=unit["_TypeName"], Switchtype=unit["_Switchtype"], Options=unit["_Options"]).Create() # Read initial state self.UpdateStatus() DumpConfigToLog() return
def main(): """call this to launch lerpn """ debug = os.getenv("DEBUG_LERPN") if debug is not None and int(debug): import rpdb rpdb.set_trace() if "--help" in sys.argv or "-h" in sys.argv: print("usage: %s [--version] [--help]" % os.path.basename(sys.argv[0])) print("") print("lerpn (Linux Engineering RPN calculator)") print("Run with no arguments to start the calculator. Once started, try") print("pressing ? to see a list of commands.") return if "--version" in sys.argv: print("lerpn version " + __version__) return curses.wrapper(wrapped_main)
def onStart(self): # Debug debug = 0 if (Parameters["Mode1"] != "none"): Domoticz.Debugging(1) debug = 1 if (Parameters["Mode1"] == 'ptvsd'): Domoticz.Log("Debugger ptvsd started, use 0.0.0.0:5678 to attach") import ptvsd # signal error on raspberry ptvsd.enable_attach() ptvsd.wait_for_attach() elif (Parameters["Mode1"] == 'rpdb'): Domoticz.Log( "Debugger rpdb started, use 'telnet 0.0.0.0 4444' to connect") import rpdb rpdb.set_trace() # signal error on raspberry # rpdb.handle_trap("0.0.0.0", 4444) # Heartbeat self.heartbeat = Heartbeat(int(Parameters["Mode2"])) self.heartbeat.setHeartbeat(self.AutoConnect) # Serial Connection usb = Parameters["Mode3"] self.serialConn = Domoticz.Connection(Name="Usb", Transport="Serial", Protocol="Line", Address=usb, Baud=57600) self.serialConn.Connect() self.CreateDevice() return
def onStart(self): # Debug debug = 0 if Parameters["Mode1"] != "none": Domoticz.Debugging(1) debug = 1 if Parameters["Mode1"] == "ptvsd": Domoticz.Log("Debugger ptvsd started, use 0.0.0.0:5678 to attach") import ptvsd # signal error on raspberry ptvsd.enable_attach() ptvsd.wait_for_attach() elif Parameters["Mode1"] == "rpdb": Domoticz.Log( "Debugger rpdb started, use 'telnet 127.0.0.1 4444' on host to connect" ) import rpdb rpdb.set_trace() # signal error on raspberry # rpdb.handle_trap("0.0.0.0", 4444) self.UpdateThread.start() # Heartbeat self.heartbeat = Heartbeat(int(Parameters["Mode2"])) if Parameters["Mode4"] == "None": Domoticz.Error("No model name set. Stop") self.heartbeat.setHeartbeat(self.doNothing) return else: self.heartbeat.setHeartbeat(self.UpdateStatus) Domoticz.Log("python-miio library version: " + miio.__version__) # Create miio ip = Parameters["Address"] token = Parameters["Mode3"] if Parameters["Mode4"] == "h": self.miio = miio.airpurifier_miot.AirPurifierMiot(ip, token, 0, debug, True) self.__UNITS = self.__UNITS_B + self.__UNITS_H elif Parameters["Mode4"] == "c": try: self.miio = miio.airpurifier_miot.AirPurifierMB4( ip, token, 0, debug, True ) self.__UNITS = self.__UNITS_B + self.__UNITS_C except: Domoticz.Error("AirPurifierMB4 not available, update Miio library") self.heartbeat.setHeartbeat(self.doNothing) Domoticz.Debug( "Xiaomi AirPurifier created with address '" + ip + "' and token '" + token + "'" ) # Read initial state self.UpdateStatus() DumpConfigToLog() return
import sys import numpy as np import bdb import rpdb #import pdb x = 2 d = 4 rpdb.set_trace() b = bdb.Bdb() f = np.array([1]) y = 3 * x - d a = 2 b = 3 a = 4 print(a + b)
def ws(self): # you can access the class instance through import rpdb rpdb.set_trace() handler = cherrypy.request.ws_handler
def step_impl(context): import rpdb rpdb.set_trace()
%bg # run in the background %%javascript # and many other languages from IPython.display import HTML, SVG; HTML(html_string) # render HTML, SVG ipython notebook # D3 support : wrobstory/sticky ipython nbconvert --to [html|latex|slides|markdown|rst|python] # PDB tricks !p = ... # make it possible to start a cmdline with pdb shorthands debug foo() # step into a function with pdb import pdb; foo(42); pdb.pm() # enter debugger post-mortem using: sys.last_traceback / sys.last_value # non-handled exception info from IPython.core.debugger import Pdb; Pdb().set_trace() ipdb.set_trace() / python -mipdb / ipdb.pm() / ipdb.runcall(function, arg) pdbpp # prettier PDB google/pyringe # when python itself crashes, gets stuck in some C extension, or you want to inspect data without stopping a program import rpdb; rpdb.set_trace() # remote debugging from pdb_clone import pdb; pdb.set_trace_remote() # then pdb-attach : remote-debugging - Also: pdbhandler.register() to enter at any time a running program boltons.debugutils.pdb_on_signal from pprint import pprint # indent=4 vars(obj), dir(obj) inspect.getmembers(obj) inspect.getargspec(foo_func) # get signature inspect.getfile(my_module) inspect.getsource(foo_func) # if implemented in C, use punchagan/cinspect frame,filename,line_number,function_name,lines,index=inspect.getouterframes(inspect.currentframe())[1] inspect.currentframe(1).f_locals['foo'] = 'overriding caller local variable!' # http://code.activestate.com/recipes/439096-get-the-value-of-a-cell-from-a-closure/
def main(): # initialize module = AnsibleModule( argument_spec=dict( name=dict(type='str', aliases=['service', 'unit']), state=dict(type='str', choices=['reloaded', 'restarted', 'started', 'stopped']), enabled=dict(type='bool'), force=dict(type='bool'), masked=dict(type='bool'), daemon_reload=dict(type='bool', default=False, aliases=['daemon-reload']), user=dict(type='bool'), scope=dict(type='str', choices=['system', 'user', 'global']), no_block=dict(type='bool', default=False), ), supports_check_mode=True, required_one_of=[['state', 'enabled', 'masked', 'daemon_reload']], mutually_exclusive=[['scope', 'user']], ) import rpdb rpdb.set_trace(addr="0.0.0.0") systemctl = module.get_bin_path('systemctl', True) ''' Set CLI options depending on params ''' if module.params['user'] is not None: # handle user deprecation, mutually exclusive with scope module.deprecate("The 'user' option is being replaced by 'scope'", version='2.11') if module.params['user']: module.params['scope'] = 'user' else: module.params['scope'] = 'system' # if scope is 'system' or None, we can ignore as there is no extra switch. # The other choices match the corresponding switch if module.params['scope'] not in (None, 'system'): systemctl += " --%s" % module.params['scope'] if module.params['no_block']: systemctl += " --no-block" if module.params['force']: systemctl += " --force" unit = module.params['name'] rc = 0 out = err = '' result = dict( name=unit, changed=False, status=dict(), ) for requires in ('state', 'enabled', 'masked'): if module.params[requires] is not None and unit is None: module.fail_json(msg="name is also required when specifying %s" % requires) # Run daemon-reload first, if requested if module.params['daemon_reload'] and not module.check_mode: (rc, out, err) = module.run_command("%s daemon-reload" % (systemctl)) if rc != 0: module.fail_json(msg='failure %d during daemon-reload: %s' % (rc, err)) if unit: found = False is_initd = sysv_exists(unit) is_systemd = False # check service data, cannot error out on rc as it changes across versions, assume not found (rc, out, err) = module.run_command("%s show '%s'" % (systemctl, unit)) if request_was_ignored(out) or request_was_ignored(err): # fallback list-unit-files as show does not work on some systems (chroot) # not used as primary as it skips some services (like those using init.d) and requires .service/etc notation (rc, out, err) = module.run_command("%s list-unit-files '%s'" % (systemctl, unit)) if rc == 0: is_systemd = True elif rc == 0: # load return of systemctl show into dictionary for easy access and return if out: result['status'] = parse_systemctl_show( to_native(out).split('\n')) is_systemd = 'LoadState' in result[ 'status'] and result['status']['LoadState'] != 'not-found' is_masked = 'LoadState' in result['status'] and result[ 'status']['LoadState'] == 'masked' # Check for loading error if is_systemd and not is_masked and 'LoadError' in result[ 'status']: module.fail_json(msg="Error loading unit file '%s': %s" % (unit, result['status']['LoadError'])) else: # Check for systemctl command module.run_command(systemctl, check_rc=True) # Does service exist? found = is_systemd or is_initd if is_initd and not is_systemd: module.warn( 'The service (%s) is actually an init script but the system is managed by systemd' % unit) # mask/unmask the service, if requested, can operate on services before they are installed if module.params['masked'] is not None: # state is not masked unless systemd affirms otherwise masked = ('LoadState' in result['status'] and result['status']['LoadState'] == 'masked') if masked != module.params['masked']: result['changed'] = True if module.params['masked']: action = 'mask' else: action = 'unmask' if not module.check_mode: (rc, out, err) = module.run_command( "%s %s '%s'" % (systemctl, action, unit)) if rc != 0: # some versions of system CAN mask/unmask non existing services, we only fail on missing if they don't fail_if_missing(module, found, unit, msg='host') # Enable/disable service startup at boot if requested if module.params['enabled'] is not None: if module.params['enabled']: action = 'enable' else: action = 'disable' fail_if_missing(module, found, unit, msg='host') # do we need to enable the service? enabled = False (rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit)) # check systemctl result or if it is a init script if rc == 0: enabled = True elif rc == 1: # if not a user or global user service and both init script and unit file exist stdout should have enabled/disabled, otherwise use rc entries if module.params['scope'] in (None, 'system') and \ not module.params['user'] and \ is_initd and \ not out.strip().endswith('disabled') and \ sysv_is_enabled(unit): enabled = True # default to current state result['enabled'] = enabled # Change enable/disable if needed if enabled != module.params['enabled']: result['changed'] = True if not module.check_mode: (rc, out, err) = module.run_command( "%s %s '%s'" % (systemctl, action, unit)) if rc != 0: module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, out + err)) result['enabled'] = not enabled # set service state if requested if module.params['state'] is not None: fail_if_missing(module, found, unit, msg="host") # default to desired state result['state'] = module.params['state'] # What is current service state? if 'ActiveState' in result['status']: action = None if module.params['state'] == 'started': if not is_running_service(result['status']): action = 'start' elif module.params['state'] == 'stopped': if is_running_service(result['status']): action = 'stop' else: if not is_running_service(result['status']): action = 'start' else: action = module.params[ 'state'][: -2] # remove 'ed' from restarted/reloaded result['state'] = 'started' if action: result['changed'] = True if not module.check_mode: (rc, out, err) = module.run_command( "%s %s '%s'" % (systemctl, action, unit)) if rc != 0: module.fail_json( msg="Unable to %s service %s: %s" % (action, unit, err)) else: # this should not happen? module.fail_json(msg="Service is in unknown state", status=result['status']) module.exit_json(**result)
import rpdb rpdb.set_trace(addr='0.0.0.0', port=4444)
def main(): print("Before stop in debugger") rpdb.set_trace() # The debugger port by default is 4444 testFunc()
def main(): # initialize module = AnsibleModule( argument_spec=dict( name=dict(type='str', aliases=['service', 'unit']), state=dict(type='str', choices=['reloaded', 'restarted', 'started', 'stopped']), enabled=dict(type='bool'), force=dict(type='bool'), masked=dict(type='bool'), daemon_reload=dict(type='bool', default=False, aliases=['daemon-reload']), daemon_reexec=dict(type='bool', default=False, aliases=['daemon-reexec']), scope=dict(type='str', default='system', choices=['system', 'user', 'global']), no_block=dict(type='bool', default=False), ), supports_check_mode=True, required_one_of=[[ 'state', 'enabled', 'masked', 'daemon_reload', 'daemon_reexec' ]], required_by=dict( state=('name', ), enabled=('name', ), masked=('name', ), ), ) unit = module.params['name'] if unit is not None: for globpattern in (r"*", r"?", r"["): if globpattern in unit: module.fail_json( msg= "This module does not currently support using glob patterns, found '%s' in service name: %s" % (globpattern, unit)) import rpdb rpdb.set_trace(addr="0.0.0.0") systemctl = module.get_bin_path('systemctl', True) if os.getenv('XDG_RUNTIME_DIR') is None: os.environ['XDG_RUNTIME_DIR'] = '/run/user/%s' % os.geteuid() ''' Set CLI options depending on params ''' # if scope is 'system' or None, we can ignore as there is no extra switch. # The other choices match the corresponding switch if module.params['scope'] != 'system': systemctl += " --%s" % module.params['scope'] if module.params['no_block']: systemctl += " --no-block" if module.params['force']: systemctl += " --force" rc = 0 out = err = '' result = dict( name=unit, changed=False, status=dict(), ) # Run daemon-reload first, if requested if module.params['daemon_reload'] and not module.check_mode: (rc, out, err) = module.run_command("%s daemon-reload" % (systemctl)) if rc != 0: module.fail_json(msg='failure %d during daemon-reload: %s' % (rc, err)) # Run daemon-reexec if module.params['daemon_reexec'] and not module.check_mode: (rc, out, err) = module.run_command("%s daemon-reexec" % (systemctl)) if rc != 0: module.fail_json(msg='failure %d during daemon-reexec: %s' % (rc, err)) if unit: found = False is_initd = sysv_exists(unit) is_systemd = False # check service data, cannot error out on rc as it changes across versions, assume not found (rc, out, err) = module.run_command("%s show '%s'" % (systemctl, unit)) if rc == 0 and not (request_was_ignored(out) or request_was_ignored(err)): # load return of systemctl show into dictionary for easy access and return if out: result['status'] = parse_systemctl_show( to_native(out).split('\n')) is_systemd = 'LoadState' in result[ 'status'] and result['status']['LoadState'] != 'not-found' is_masked = 'LoadState' in result['status'] and result[ 'status']['LoadState'] == 'masked' # Check for loading error if is_systemd and not is_masked and 'LoadError' in result[ 'status']: module.fail_json(msg="Error loading unit file '%s': %s" % (unit, result['status']['LoadError'])) # Workaround for https://github.com/ansible/ansible/issues/71528 elif err and rc == 1 and 'Failed to parse bus message' in err: result['status'] = parse_systemctl_show(to_native(out).split('\n')) unit_base, sep, suffix = unit.partition('@') unit_search = '{unit_base}{sep}'.format(unit_base=unit_base, sep=sep) (rc, out, err) = module.run_command( "{systemctl} list-unit-files '{unit_search}*'".format( systemctl=systemctl, unit_search=unit_search)) is_systemd = unit_search in out (rc, out, err) = module.run_command( "{systemctl} is-active '{unit}'".format(systemctl=systemctl, unit=unit)) result['status']['ActiveState'] = out.rstrip('\n') else: # list taken from man systemctl(1) for systemd 244 valid_enabled_states = [ "enabled", "enabled-runtime", "linked", "linked-runtime", "masked", "masked-runtime", "static", "indirect", "disabled", "generated", "transient" ] (rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit)) if out.strip() in valid_enabled_states: is_systemd = True else: # fallback list-unit-files as show does not work on some systems (chroot) # not used as primary as it skips some services (like those using init.d) and requires .service/etc notation (rc, out, err) = module.run_command("%s list-unit-files '%s'" % (systemctl, unit)) if rc == 0: is_systemd = True else: # Check for systemctl command module.run_command(systemctl, check_rc=True) # Does service exist? found = is_systemd or is_initd if is_initd and not is_systemd: module.warn( 'The service (%s) is actually an init script but the system is managed by systemd' % unit) # mask/unmask the service, if requested, can operate on services before they are installed if module.params['masked'] is not None: # state is not masked unless systemd affirms otherwise (rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit)) masked = out.strip() == "masked" if masked != module.params['masked']: result['changed'] = True if module.params['masked']: action = 'mask' else: action = 'unmask' if not module.check_mode: (rc, out, err) = module.run_command( "%s %s '%s'" % (systemctl, action, unit)) if rc != 0: # some versions of system CAN mask/unmask non existing services, we only fail on missing if they don't fail_if_missing(module, found, unit, msg='host') # Enable/disable service startup at boot if requested if module.params['enabled'] is not None: if module.params['enabled']: action = 'enable' else: action = 'disable' fail_if_missing(module, found, unit, msg='host') # do we need to enable the service? enabled = False (rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit)) # check systemctl result or if it is a init script if rc == 0: enabled = True elif rc == 1: # if not a user or global user service and both init script and unit file exist stdout should have enabled/disabled, otherwise use rc entries if module.params['scope'] == 'system' and \ is_initd and \ not out.strip().endswith('disabled') and \ sysv_is_enabled(unit): enabled = True # default to current state result['enabled'] = enabled # Change enable/disable if needed if enabled != module.params['enabled']: result['changed'] = True if not module.check_mode: (rc, out, err) = module.run_command( "%s %s '%s'" % (systemctl, action, unit)) if rc != 0: module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, out + err)) result['enabled'] = not enabled # set service state if requested if module.params['state'] is not None: fail_if_missing(module, found, unit, msg="host") # default to desired state result['state'] = module.params['state'] # What is current service state? if 'ActiveState' in result['status']: action = None if module.params['state'] == 'started': if not is_running_service(result['status']): action = 'start' elif module.params['state'] == 'stopped': if is_running_service( result['status']) or is_deactivating_service( result['status']): action = 'stop' else: if not is_running_service(result['status']): action = 'start' else: action = module.params[ 'state'][: -2] # remove 'ed' from restarted/reloaded result['state'] = 'started' if action: result['changed'] = True if not module.check_mode: (rc, out, err) = module.run_command( "%s %s '%s'" % (systemctl, action, unit)) if rc != 0: module.fail_json( msg="Unable to %s service %s: %s" % (action, unit, err)) # check for chroot elif is_chroot(module) or os.environ.get('SYSTEMD_OFFLINE') == '1': module.warn( "Target is a chroot or systemd is offline. This can lead to false positives or prevent the init system tools from working." ) else: # this should not happen? module.fail_json(msg="Service is in unknown state", status=result['status']) module.exit_json(**result)
for fib in fibonacci.xfibonacci(num=num, max=max): yield factor(fib) def factor(num): factors = [] for factor in xfactor(num): factors.append(factor) return factors def xfactor(num): for prime in primes.xprimes(max=num): while num % prime == 0: yield prime num /= prime if __name__ == "__main__": listening = True if len(sys.argv) > 1: if sys.argv[1] == "listening": listening = True socket_addr = ("", 59000) elif sys.argv[1] == "not_listening": listening = False socket_addr = ("localhost", 57000) rpdb.set_trace(listening=listening, socket_addr=socket_addr) factor_fibonacci(num=2)
def home(): import rpdb rpdb.set_trace('0.0.0.0') return 'Hello World!'
def set_trace(): if config.DEBUG: if config.REMOTE_DEBUGGING: pdb.set_trace(addr=config.DEBUG_ADDR, port=config.DEBUG_PORT) else: pdb.set_trace()