Python sys.exit() Examples

The following are 30 code examples of sys.exit(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: whitelist.py    From cloudflare-tor-whitelister with GNU General Public License v2.0 12 votes vote down vote up
def retrieve_top_tor_exit_ips(limit=CLOUDFLARE_ACCESS_RULE_LIMIT):
    """
    Retrieve exit information from Onionoo sorted by consensus weight
    """
    exits = {}
    params = {
        'running': True,
        'flag': 'Exit',
        'fields': 'or_addresses,exit_probability',
        'order': '-consensus_weight',
        'limit': limit
    }
    r = requests.get("https://onionoo.torproject.org/details", params=params)
    r.raise_for_status()
    res = r.json()
    for relay in res.get('relays'):
        or_address = relay.get('or_addresses')[0].split(':')[0]
        exit_probability = relay.get('exit_probability', 0.0)
        # Try calculate combined weight for all relays on each IP
        exits[or_address] = exits.get(or_address, 0.0) + exit_probability
    return sorted(exits, key=exits.get, reverse=True) 
Example #2
Source File: reval_discovery.py    From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License 11 votes vote down vote up
def parse_args():
  """
  Parse input arguments
  """
  parser = argparse.ArgumentParser(description='Re-evaluate results')
  parser.add_argument('output_dir', nargs=1, help='results directory',
                      type=str)
  parser.add_argument('--imdb', dest='imdb_name',
                      help='dataset to re-evaluate',
                      default='voc_2007_test', type=str)
  parser.add_argument('--comp', dest='comp_mode', help='competition mode',
                      action='store_true')

  if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(1)

  args = parser.parse_args()
  return args 
Example #3
Source File: setup.py    From keras_mixnets with MIT License 7 votes vote down vote up
def run(self):
        try:
            self.status('Removing previous builds...')
            rmtree(os.path.join(base_path, 'dist'))
        except OSError:
            pass

        self.status('Building Source and Wheel (universal) distribution...')
        os.system('{0} setup.py sdist bdist_wheel'.format(sys.executable))

        self.status('Pushing git tags...')
        os.system('git tag v{0}'.format(get_version()))
        os.system('git push --tags')

        try:
            self.status('Removing build artifacts...')
            rmtree(os.path.join(base_path, 'build'))
            rmtree(os.path.join(base_path, '{}.egg-info'.format(PACKAGE_NAME)))
        except OSError:
            pass

        sys.exit() 
Example #4
Source File: kerberos.py    From incubator-spot with Apache License 2.0 7 votes vote down vote up
def __init__(self):

        self._logger = Util.get_logger('SPOT.COMMON.KERBEROS')
        principal, keytab, sasl_mech, security_proto = config.kerberos()

        if os.getenv('KINITPATH'):
            self._kinit = os.getenv('KINITPATH')
        else:
            self._kinit = "kinit"

        self._kinitopts = os.getenv('KINITOPTS')
        self._keytab = "-kt {0}".format(keytab)
        self._krb_user = principal

        if self._kinit == None or self._keytab == None or self._krb_user == None:
            self._logger.error("Please verify kerberos configuration, some environment variables are missing.")
            sys.exit(1)

        if self._kinitopts is None:
            self._kinit_cmd = "{0} {1} {2}".format(self._kinit, self._keytab, self._krb_user)
        else:
            self._kinit_cmd = "{0} {1} {2} {3}".format(self._kinit, self._kinitopts, self._keytab, self._krb_user) 
Example #5
Source File: eapi_2_acl.py    From Mastering-Python-Networking-Second-Edition with MIT License 7 votes vote down vote up
def getEndpoints(switchHostnames, protocol, username, password):
   """ Check that each server is up, and return a mapping from
   hostname to jsonrpclib.Server """
   apiEndpoints = {} # mapping from hostname to the API endpoint
   for switch in switchHostnames:
      url = "{protocol}://{user}:{pw}@{hostname}/command-api".format(
         protocol=protocol, user=username, pw=password, hostname=switch)
      server = jsonrpclib.Server(url)
      try:
         # We should at least be able to 'enable'
         server.runCmds(1, ["enable"])
      except Exception as e:
         print "Unable to run 'enable' on switch", e
         sys.exit(1)
      apiEndpoints[switch] = server
   return apiEndpoints 
Example #6
Source File: util.py    From wechat-alfred-workflow with MIT License 7 votes vote down vote up
def __call__(self, *args, **kwargs):
        """Trap ``SIGTERM`` and call wrapped function."""
        self._caught_signal = None
        # Register handler for SIGTERM, then call `self.func`
        self.old_signal_handler = signal.getsignal(signal.SIGTERM)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.func(*args, **kwargs)

        # Restore old signal handler
        signal.signal(signal.SIGTERM, self.old_signal_handler)

        # Handle any signal caught during execution
        if self._caught_signal is not None:
            signum, frame = self._caught_signal
            if callable(self.old_signal_handler):
                self.old_signal_handler(signum, frame)
            elif self.old_signal_handler == signal.SIG_DFL:
                sys.exit(0) 
Example #7
Source File: plugins.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def __init__(self, bus):
        self.bus = bus
        # Set default handlers
        self.handlers = {'SIGTERM': self.bus.exit,
                         'SIGHUP': self.handle_SIGHUP,
                         'SIGUSR1': self.bus.graceful,
                         }

        if sys.platform[:4] == 'java':
            del self.handlers['SIGUSR1']
            self.handlers['SIGUSR2'] = self.bus.graceful
            self.bus.log('SIGUSR1 cannot be set on the JVM platform. '
                         'Using SIGUSR2 instead.')
            self.handlers['SIGINT'] = self._jython_SIGINT_handler

        self._previous_handlers = {}
        # used to determine is the process is a daemon in `self._is_daemonized`
        self._original_pid = os.getpid() 
Example #8
Source File: app.py    From svviz with MIT License 6 votes vote down vote up
def checkRequirements(args):
    if not remap.check_swalign():
        print("ERROR: check that svviz is correctly installed -- the 'ssw' Smith-Waterman alignment module does not appear to be functional")
        sys.exit(1)
    if args.export:
        exportFormat = export.getExportFormat(args)
        converter = export.getExportConverter(args, exportFormat)
        if converter is None and exportFormat != "svg":
            if args.converter is not None:
                logging.error("ERROR: unable to run SVG converter '{}'. Please check that it is "
                    "installed correctly".format(args.converter))
            else:
                logging.error("ERROR: unable to export to PDF/PNG because at least one of the following "
                    "programs must be correctly installed: webkitToPDF, librsvg or inkscape")

            sys.exit(1) 
Example #9
Source File: setup.py    From django-rest-polymorphic with MIT License 6 votes vote down vote up
def run(self):
        try:
            self.status('Removing previous builds…')
            rmtree(os.path.join(here, 'dist'))
        except OSError:
            pass

        self.status('Building Source and Wheel (universal) distribution…')
        os.system('{0} setup.py sdist bdist_wheel --universal'.format(
            sys.executable
        ))

        self.status('Uploading the package to PyPi via Twine…')
        os.system('twine upload dist/*')

        sys.exit() 
Example #10
Source File: remote_voice.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _rotateLeft(self, amnt):
        #TARGET VELOCITY
        X = 0.0
        Y = 0.0
        Theta = 0.5

        try:
            self.motion.moveToward(X, Y, Theta)
        except KeyboardInterrupt:
            print "KeyBoard Interrupt initiated"
            self.motion.stopMove()
            exit()
        except Exception, errorMsg:
            print str(errorMsg)
            print "This example is not allowed on this robot."
            exit() 
Example #11
Source File: quicktest.py    From django-classified with MIT License 6 votes vote down vote up
def _tests(self):
        settings.configure(
            DEBUG=True,
            DATABASES={
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': os.path.join(self.DIRNAME, 'database.db'),
                }
            },
            INSTALLED_APPS=self.INSTALLED_APPS + self.apps,
            MIDDLEWARE=self.MIDDLEWARE,
            ROOT_URLCONF='django_classified.tests.urls',
            STATIC_URL='/static/',
            TEMPLATES=self.TEMPLATES,
            SITE_ID=1
        )

        from django.test.runner import DiscoverRunner
        test_runner = DiscoverRunner()
        django.setup()

        failures = test_runner.run_tests(self.apps)
        if failures:
            sys.exit(failures) 
Example #12
Source File: export.py    From svviz with MIT License 6 votes vote down vote up
def getExportConverter(args, exportFormat):
    if args.converter == "webkittopdf" and exportFormat=="png":
        logging.error("webkitToPDF does not support export to PNG; use librsvg or inkscape instead, or "
            "export to PDF")
        sys.exit(1)

    if exportFormat == "png" and args.converter is None:
        return "librsvg"

    if args.converter == "rsvg-convert":
        return "librsvg"

    if args.converter in [None, "webkittopdf"]:
        if checkWebkitToPDF():
            return "webkittopdf"

    if args.converter in [None, "librsvg"]:
        if checkRSVGConvert():
            return "librsvg"

    if args.converter in [None, "inkscape"]:
        if checkInkscape():
            return "inkscape"

    return None 
Example #13
Source File: start_oa.py    From incubator-spot with Apache License 2.0 6 votes vote down vote up
def validate_parameters_values(args,logger):

    logger.info("Validating input parameter values")

    #date.
    is_date_ok = True if len(args.date) == 8 else False

    # type
    dirs = os.walk(script_path).next()[1]
    is_type_ok = True if args.type in dirs else False

    #limit
    try:
        int(args.limit)
        is_limit_ok = True
    except ValueError:
        is_limit_ok = False

    if not is_date_ok: logger.error("date parameter is not correct, please validate it")
    if not is_type_ok: logger.error("type parameter is not supported, please select a valid type")
    if not is_limit_ok: logger.error("limit parameter is not correct, please select a valid limit")
    if not is_date_ok or not is_type_ok or not is_limit_ok: sys.exit(1) 
Example #14
Source File: proxy_oa.py    From incubator-spot with Apache License 2.0 6 votes vote down vote up
def _get_proxy_results(self):

        self._logger.info("Getting {0} Machine Learning Results from HDFS".format(self._date))
        proxy_results = "{0}/proxy_results.csv".format(self._data_path)

        # get hdfs path from conf file.
        HUSER = self._spot_conf.get('conf', 'HUSER').replace("'", "").replace('"', '')
        hdfs_path = "{0}/proxy/scored_results/{1}/scores/proxy_results.csv".format(HUSER,self._date)

        # get results file from hdfs.
        get_command = Util.get_ml_results_form_hdfs(hdfs_path,self._data_path)
        self._logger.info("{0}".format(get_command))

         # valdiate files exists
        if os.path.isfile(proxy_results):

            # read number of results based in the limit specified.
            self._logger.info("Reading {0} proxy results file: {1}".format(self._date,proxy_results))
            self._proxy_results = Util.read_results(proxy_results,self._limit,self._results_delimiter)[:]
            if len(self._proxy_results) == 0: self._logger.error("There are not proxy results.");sys.exit(1)
        else:
            self._logger.error("There was an error getting ML results from HDFS")
            sys.exit(1)

        self._proxy_scores = self._proxy_results[:] 
Example #15
Source File: llvm.py    From godot-mono-builds with MIT License 6 votes vote down vote up
def main(raw_args):
    import cmd_utils

    parser = cmd_utils.build_arg_parser(description='Builds LLVM for Mono')

    default_help = 'default: %(default)s'

    parser.add_argument('action', choices=['make', 'clean'])
    parser.add_argument('--target', choices=target_values, action='append', required=True)

    cmd_utils.add_base_arguments(parser, default_help)

    args = parser.parse_args(raw_args)

    opts = base_opts_from_args(args)
    targets = args.target

    try:
        for target in targets:
            action = { 'make': make, 'clean': clean }[args.action]
            action(opts, target)
    except BuildError as e:
        sys.exit(e.message) 
Example #16
Source File: human_greeter_with_awareness.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def __init__(self, app):
        """
        Initialisation of qi framework and event detection.
        """
        super(HumanTrackedEventWatcher, self).__init__()

        try:
            app.start()
        except RuntimeError:
            print ("Can't connect to Naoqi at ip \"" + args.ip + "\" on port " +
                   str(args.port) + ".\n")

            sys.exit(1)

        session = app.session
        self.subscribers_list = []
        self.is_speech_reco_started = False

        # SUBSCRIBING SERVICES
        self.tts             = session.service("ALTextToSpeech")
        self.memory          = session.service("ALMemory")
        self.motion          = session.service("ALMotion")
        self.speech_reco     = session.service("ALSpeechRecognition")
        self.basic_awareness = session.service("ALBasicAwareness") 
Example #17
Source File: remote_voice.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _moveForward(self, amnt):
        #TARGET VELOCITY
        X = 0.5  # forward
        Y = 0.0
        Theta = 0.0

        try:
            self.motion.moveToward(X, Y, Theta)
        except KeyboardInterrupt:
            print "KeyBoard Interrupt initiated"
            self.motion.stopMove()
            exit()
        except Exception, errorMsg:
            print str(errorMsg)
            print "This example is not allowed on this robot."
            exit() 
Example #18
Source File: remote_voice.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _rotateRight(self, amnt):
        #TARGET VELOCITY
        X = 0.0
        Y = 0.0
        Theta = -0.5

        try:
            self.motion.moveToward(X, Y, Theta)
        except KeyboardInterrupt:
            print "KeyBoard Interrupt initiated"
            self.motion.stopMove()
            exit()
        except Exception, errorMsg:
            print str(errorMsg)
            print "This example is not allowed on this robot."
            exit() 
Example #19
Source File: human_greeter.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def run(self):
        """
        Loop on, wait for events until manual interruption.
        """
        # start
        print "Waiting for the robot to be in wake up position"
        self.motion.wakeUp()

        print "Starting HumanGreeter"
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print "Interrupted by user, stopping HumanGreeter"
            self.face_detection.unsubscribe("HumanGreeter")
            #stop
            sys.exit(0)

        return 
Example #20
Source File: remote_terminal.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _moveForward(self, amnt):
        #TARGET VELOCITY
        X = 0.5  # forward
        Y = 0.0
        Theta = 0.0

        try:
            self.motion_service.moveToward(X, Y, Theta)
        except KeyboardInterrupt:
            print "KeyBoard Interrupt initiated"
            self.motion_service.stopMove()
            exit()
        except Exception, errorMsg:
            print str(errorMsg)
            print "This example is not allowed on this robot."
            exit() 
Example #21
Source File: remote_terminal.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _moveBackward(self, amnt):
        #TARGET VELOCITY
        X = -0.5  # backward
        Y = 0.0
        Theta = 0.0

        try:
            self.motion_service.moveToward(X, Y, Theta)
        except KeyboardInterrupt:
            print "KeyBoard Interrupt initiated"
            self.motion_service.stopMove()
            exit()
        except Exception, errorMsg:
            print str(errorMsg)
            print "This example is not allowed on this robot."
            exit() 
Example #22
Source File: remote_terminal.py    From pepper-robot-programming with MIT License 6 votes vote down vote up
def _rotateLeft(self, amnt):
        #TARGET VELOCITY
        X = 0.0
        Y = 0.0
        Theta = 0.5

        try:
            self.motion_service.moveToward(X, Y, Theta)
        except KeyboardInterrupt:
            print "KeyBoard Interrupt initiated"
            self.motion_service.stopMove()
            exit()
        except Exception, errorMsg:
            print str(errorMsg)
            print "This example is not allowed on this robot."
            exit() 
Example #23
Source File: arm_now.py    From arm_now with MIT License 6 votes vote down vote up
def check_dependencies_or_exit():
    dependencies = [
            which("e2cp",
                ubuntu="apt-get install e2tools",
                arch="yaourt -S e2tools",
                darwin="brew install e2tools gettext e2fsprogs\nbrew unlink e2fsprogs && brew link e2fsprogs -f"),
            which("qemu-system-arm",
                  ubuntu="apt-get install qemu",
                  kali="apt-get install qemu-system",
                  arch="pacman -S qemu-arch-extra",
                  darwin="brew install qemu"),
            which("unzip",
                ubuntu="apt-get install unzip",
                arch="pacman -S unzip",
                darwin="brew install unzip")
            ]
    if not all(dependencies):
        print("requirements missing, plz install them", file=sys.stderr)
        sys.exit(1) 
Example #24
Source File: eapi_2_acl.py    From Mastering-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def applyChanges(aclName, apiEndpoints, aclRules):
   """ Given the switch mapping and a list of the new ACL rules, apply
   the ACL to each switch """
   cmdList = ["enable",
              "configure",
              # Not the most efficient way to clear an ACL:
                 "no ip access-list %s" % aclName,
              # Now enter configuration mode for the ACL:
                 "ip access-list %s" % aclName]
   cmdList = cmdList + aclRules + ["exit"]
   
   for hostname, apiEndpoint in apiEndpoints.iteritems():
      print "Updating access list on switch", hostname, "....",
      try:
         apiEndpoint.runCmds(1, cmdList)
      except jsonrpclib.ProtocolError as e:
         print "[ERROR]"
         print "  ", e
         # jsonrpclib isn't very friendly at getting the error data as
         # specified by the spec. This is a shortcut for getting the
         # last error:
         errorResponse = jsonrpclib.loads(jsonrpclib.history.response)
         print "   Details:", errorResponse["error"]["data"][-1]["errors"]
      else:
         print "[SUCCESS]" 
Example #25
Source File: local.py    From ALF with Apache License 2.0 6 votes vote down vote up
def load_project(project_name):
    # load project and check that it looks okay
    try:
        importlib.import_module(project_name)
    except ImportError as e:
        try:
            #TODO: relative module imports in a projects/Project will fail for some reason
            importlib.import_module("projects.%s" % project_name)
        except ImportError as e:
            log.error("Failed to import project %s", project_name, exc_info=1)
            sys.exit(1)
    if len(_registered) != 1:
        log.error("Project must register itself using alf.register(). "
                  "%d projects registered, expecting 1.", len(_registered))
        sys.exit(1)
    project_cls = _registered.pop()
    if not issubclass(project_cls, Fuzzer):
        raise TypeError("Expecting a Fuzzer, not '%s'" % type(project_cls))
    return project_cls 
Example #26
Source File: reval.py    From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License 6 votes vote down vote up
def parse_args():
  """
  Parse input arguments
  """
  parser = argparse.ArgumentParser(description='Re-evaluate results')
  parser.add_argument('output_dir', nargs=1, help='results directory',
                      type=str)
  parser.add_argument('--imdb', dest='imdb_name',
                      help='dataset to re-evaluate',
                      default='voc_2007_test', type=str)
  parser.add_argument('--matlab', dest='matlab_eval',
                      help='use matlab for evaluation',
                      action='store_true')
  parser.add_argument('--comp', dest='comp_mode', help='competition mode',
                      action='store_true')
  parser.add_argument('--nms', dest='apply_nms', help='apply nms',
                      action='store_true')

  if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(1)

  args = parser.parse_args()
  return args 
Example #27
Source File: twitter-export-image-fill.py    From twitter-export-image-fill with The Unlicense 6 votes vote down vote up
def find_youtube_dl():
  if not args.skip_videos:
    if args.PATH_TO_YOUTUBE_DL:
      if not os.path.isfile(args.PATH_TO_YOUTUBE_DL):
        print("Could not find youtube-dl executable.")
        print("Make sure you're pointing at the right file.")
        print("A typical path would be: /usr/local/bin/youtube-dl")
        sys.exit(-1)

      return True, args.PATH_TO_YOUTUBE_DL
    else:
      if os.path.isfile('/usr/local/bin/youtube-dl'):
        if args.verbose:
          print("(Found youtube-dl automatically.)")
          print("")
        return True, '/usr/local/bin/youtube-dl'
  return False, '' 
Example #28
Source File: update.py    From wechat-alfred-workflow with MIT License 5 votes vote down vote up
def show_help(status=0):
        """Print help message."""
        print('Usage : update.py (check|install) '
              '[--prereleases] <github_slug> <version>')
        sys.exit(status) 
Example #29
Source File: eapi_2_acl.py    From Mastering-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def getEdits(filename):
   """ Opens an editor for the user to edit the ACL, and returns a
   list of the new ACL contents """
   editor = os.environ.get("EDITOR", "vi") # default editor is "vi"
   ret = subprocess.Popen([editor, filename]).wait()
   if ret != 0:
      print "Bad editor exit. Aborting."
      sys.exit(1)
   # Read in the file as a list of lines
   aclContents = open(filename, "r").readlines()
   print "New access list:"
   print "  ", "   ".join(aclContents) 
   print
   return aclContents 
Example #30
Source File: demo.py    From svviz with MIT License 5 votes vote down vote up
def loadDemo(which="example1", autoDownload=False):
    if not checkForDemo(which, autoDownload):
        sys.exit(1)

    demodir = "svviz-examples/{}".format(which)
    info = open("{}/info.txt".format(demodir))
    cmd = None
    for line in info:
        if line.startswith("#"):
            continue
        cmd = line.strip().split()
        cmd = [c.format(data=demodir) for c in cmd]
        break

    return cmd