Python sys.exit() Examples
The following are 30 code examples for showing how to use sys.exit(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
sys
, or try the search function
.
Example 1
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection Author: Sunarker File: reval_discovery.py License: MIT License | 9 votes |
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 2
Project: cloudflare-tor-whitelister Author: DonnchaC File: whitelist.py License: GNU General Public License v2.0 | 8 votes |
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 3
Project: django-classified Author: slyapustin File: quicktest.py License: MIT License | 6 votes |
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 4
Project: django-rest-polymorphic Author: apirobot File: setup.py License: MIT License | 6 votes |
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 5
Project: svviz Author: svviz File: app.py License: MIT License | 6 votes |
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 6
Project: svviz Author: svviz File: export.py License: MIT License | 6 votes |
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 7
Project: incubator-spot Author: apache File: kerberos.py License: Apache License 2.0 | 6 votes |
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 8
Project: incubator-spot Author: apache File: start_oa.py License: Apache License 2.0 | 6 votes |
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 9
Project: incubator-spot Author: apache File: proxy_oa.py License: Apache License 2.0 | 6 votes |
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 10
Project: godot-mono-builds Author: godotengine File: llvm.py License: MIT License | 6 votes |
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 11
Project: pepper-robot-programming Author: maverickjoy File: human_greeter_with_awareness.py License: MIT License | 6 votes |
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 12
Project: pepper-robot-programming Author: maverickjoy File: human_greeter.py License: MIT License | 6 votes |
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 13
Project: pepper-robot-programming Author: maverickjoy File: remote_voice.py License: MIT License | 6 votes |
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 14
Project: pepper-robot-programming Author: maverickjoy File: remote_voice.py License: MIT License | 6 votes |
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 15
Project: pepper-robot-programming Author: maverickjoy File: remote_voice.py License: MIT License | 6 votes |
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 16
Project: pepper-robot-programming Author: maverickjoy File: remote_terminal.py License: MIT License | 6 votes |
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 17
Project: pepper-robot-programming Author: maverickjoy File: remote_terminal.py License: MIT License | 6 votes |
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 18
Project: pepper-robot-programming Author: maverickjoy File: remote_terminal.py License: MIT License | 6 votes |
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 19
Project: arm_now Author: nongiach File: arm_now.py License: MIT License | 6 votes |
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 20
Project: Mastering-Python-Networking-Second-Edition Author: PacktPublishing File: eapi_2_acl.py License: MIT License | 6 votes |
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 21
Project: Mastering-Python-Networking-Second-Edition Author: PacktPublishing File: eapi_2_acl.py License: MIT License | 6 votes |
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 22
Project: keras_mixnets Author: titu1994 File: setup.py License: MIT License | 6 votes |
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 23
Project: ALF Author: blackberry File: local.py License: Apache License 2.0 | 6 votes |
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 24
Project: wechat-alfred-workflow Author: TKkk-iOSer File: util.py License: MIT License | 6 votes |
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 25
Project: Collaborative-Learning-for-Weakly-Supervised-Object-Detection Author: Sunarker File: reval.py License: MIT License | 6 votes |
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 26
Project: twitter-export-image-fill Author: mwichary File: twitter-export-image-fill.py License: The Unlicense | 6 votes |
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 27
Project: cherrypy Author: cherrypy File: plugins.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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 28
Project: unicorn-hat-hd Author: pimoroni File: paint.py License: MIT License | 5 votes |
def save(filename): try: os.mkdir('saves/') except OSError: pass try: data = unicornhathd.get_pixels() data = repr(data) data = data.replace('array', 'list') print(filename, data) file = open('saves/' + filename + '.py', 'w') file.write("""#!/usr/bin/env python import unicornhathd import signal unicornhathd.rotation(0) pixels = {} for x in range(unicornhathd.WIDTH): for y in range(unicornhathd.HEIGHT): r, g, b = pixels[x][y] unicornhathd.set_pixel(x, y, r, g, b) unicornhathd.show() print("\\nShowing: {}\\nPress Ctrl+C to exit!") signal.pause() """.format(data, filename)) file.close() os.chmod('saves/' + filename + '.py', 0o777 | stat.S_IEXEC) return("ok" + str(unicornhathd.get_pixels())) except AttributeError: print("Unable to save, please update") print("unicornhathdhathd library!") return("fail")
Example 29
Project: supervisor-logging Author: infoxchange File: __init__.py License: Apache License 2.0 | 5 votes |
def main(): """ Main application loop. """ env = os.environ try: host = env['SYSLOG_SERVER'] port = int(env['SYSLOG_PORT']) socktype = socket.SOCK_DGRAM if env['SYSLOG_PROTO'] == 'udp' \ else socket.SOCK_STREAM except KeyError: sys.exit("SYSLOG_SERVER, SYSLOG_PORT and SYSLOG_PROTO are required.") handler = SysLogHandler( address=(host, port), socktype=socktype, ) handler.setFormatter(PalletFormatter()) for event_headers, event_data in supervisor_events(sys.stdin, sys.stdout): event = logging.LogRecord( name=event_headers['processname'], level=logging.INFO, pathname=None, lineno=0, msg=event_data, args=(), exc_info=None, ) event.process = int(event_headers['pid']) handler.handle(event)
Example 30
Project: svviz Author: svviz File: demo.py License: MIT License | 5 votes |
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