sys.exit

Here are the examples of the python api sys.exit taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

23503 Examples 7

5 Source : __init__.py
with GNU General Public License v3.0
from a13xp0p0v

    def __init__(self, *opts):
        self.opts = opts
        if not self.opts:
            sys.exit('[!] ERROR: empty {} check'.format(self.__class__.__name__))
        if len(self.opts) == 1:
            sys.exit('[!] ERROR: useless {} check'.format(self.__class__.__name__))
        if not isinstance(opts[0], KconfigCheck):
            sys.exit('[!] ERROR: invalid {} check: {}'.format(self.__class__.__name__, opts))
        self.result = None

    @property

5 Source : compose_utils.py
with GNU Affero General Public License v3.0
from Abstract-Tech

def exit_cm():
    # Context manager to monkey patch sys.exit calls
    import sys

    def myexit(result_code=0):
        if result_code != 0:
            raise RuntimeError

    orig = sys.exit
    sys.exit = myexit

    try:
        yield
    finally:
        sys.exit = orig

5 Source : services.py
with MIT License
from alexmon1989

def cli():
    try:
        sys.exit(main())
    except KeyboardInterrupt:  # The user hit Control-C
        sys.stderr.write('\n\nReceived keyboard interrupt, terminating.\n\n')
        sys.stderr.flush()
        # Control-C is fatal error signal 2, for more see
        # https://tldp.org/LDP/abs/html/exitcodes.html
        sys.exit(128 + signal.SIGINT)
    except RuntimeError as exc:
        sys.stderr.write(f'\n{exc}\n\n')
        sys.stderr.flush()
        sys.exit(1)


if __name__ == '__main__':

5 Source : __init__.py
with GNU General Public License v3.0
from Artikash

def main(argv=None):
    try:
        _real_main(argv)
    except DownloadError:
        sys.exit(1)
    except SameFileError:
        sys.exit('ERROR: fixed output name but more than one file to download')
    except KeyboardInterrupt:
        sys.exit('\nERROR: Interrupted by user')

__all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']

5 Source : __init__.py
with GNU General Public License v2.0
from Atrion

def setup():
    # We want to monkey patch sys.exit so that we can get some
    # information about where exit is being called.
    newexit._old = sys.exit
    sys.exit = newexit


def teardown():

5 Source : __init__.py
with The Unlicense
from blackjack4494

def main(argv=None):
    try:
        _real_main(argv)
    except DownloadError:
        sys.exit(1)
    except SameFileError:
        sys.exit('ERROR: fixed output name but more than one file to download')
    except KeyboardInterrupt:
        sys.exit('\nERROR: Interrupted by user')


__all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']

5 Source : cli.py
with GNU Affero General Public License v3.0
from bodywork-ml

def _delete_secret(
    name: str = Argument(None), group: str = Option(None)
):
    if name:
        if not group:
            print_warn("Please specify which secrets group the secret belongs to.")
            sys.exit(1)
        else:
            delete_secret(BODYWORK_NAMESPACE, group, name)
            sys.exit(0)
    elif group:
        delete_secret_group(BODYWORK_NAMESPACE, group)
        sys.exit(0)
    else:
        print_warn("Please specify a secret or a secrets group to delete.")
        sys.exit(1)

5 Source : influx_object.py
with BSD 3-Clause "New" or "Revised" License
from Bugazelle

    def get_influxdb_version(self):
        """Function: get_influxdb_version

        :return influxdb version
        """
        try:
            req_influxdb = requests.get(self.influxdb_url, verify=False)
            response_headers = req_influxdb.headers
            influxdb_version = response_headers['X-Influxdb-Version']
            return influxdb_version
        except ConnectionError:
            sys.exit('Error: Failed to connect the influx {influxdb_url}'.format(influxdb_url=self.influxdb_url))
        except KeyError:
            sys.exit('Error: This is not a valid influx {influxdb_url}'.format(influxdb_url=self.influxdb_url))
        except requests.exceptions.SSLError:
            sys.exit('Error: SSL error when connecting influx {influxdb_url}'.format(influxdb_url=self.influxdb_url))

    def connect_influx_db(self, db_name='', org_name=''):

5 Source : qrutils.py
with GNU General Public License v3.0
from chrispetrou

def main():
    args = console()
    if args.img:
        msg = QR_Reader(args.img).decode()
        print "\n{}[+]{} QR decoded ~~> {}\n".format(BT+FG,S,msg)
        sys.exit(0)
    else:
        if args.filename is None:
            print '\n{}[x] No name provided for the output!{}\n'.format(FR,F)
            sys.exit(0)
        msg = args.msg
        Popen(['qrencode', '-o', args.filename, msg, '-s', '10'], stdout=PIPE)
        sys.exit(0)

if __name__ == '__main__':

5 Source : remove_bad_classes.py
with MIT License
from cianfrocco-lab

def checkConflicts(params):
        if params['stack'][-4:] != '.img':
        	if params['stack'][-4:] != '.hed':
                	print 'Stack extension %s is not recognized as a .hed or .img file' %(params['stack'][-4:])
                        sys.exit()

        if not os.path.exists('%s/auto_iteration_1/' %(params['folder'])):
                print "\nError: Auto_Align.py output folder does not exist. Exiting.\n"
                sys.exit()

	if not os.path.exists(params['badlist']):
		print "\nError: Bad list %s does not exist. Exiting" %(params['badlist'])
		sys.exit()

#==============================
if __name__ == "__main__":

5 Source : compare_avgs_to_3Dmodel.py
with MIT License
from cianfrocco-lab

def checkConflicts(params):
        if not params['stack']:
                print "\nWarning: no stack specified\n"
        elif not os.path.exists(params['stack']):
                print "\nError: 2D average stack file '%s' does not exist\n" % params['stack']
                sys.exit()
        if params['stack'][-4:] != '.img':
        	if params['stack'][-4:] != '.hed':
                	print 'Stack extension %s is not recognized as .hed or .img file' %(params['stack'][-4:])
                        sys.exit()

	if not os.path.exists(params['vol']):
		print 'Error: input volume does not exist.'
		sys.exit()

#==============================
def getEman2Path():

5 Source : threshold_mask_volume.py
with MIT License
from cianfrocco-lab

def checkConflicts(params):
    if params['vol'][-4:] != '.mrc':
                if params['vol'][-4:] != '.spi':
                	print 'Stack extension %s is not recognized as .spi .mrc file' %(params['vol'][-4:])
                        sys.exit()

    if os.path.exists('%s_thresh_masked%s' %(params['vol'][:-4],params['vol'][-4:])):
		print '\n Output file %s_thresh_masked%s already exists. Exiting.' %(params['vol'][:-4],params['vol'][-4:])
		sys.exit()

    if params['savemask'] is True:
        if os.path.exists('%s_thresh%s'%(params['vol'][:-4],params['vol'][-4:])):
            print '\nOutput file %s_thresh%s already exists. Exiting.'%(params['vol'][:-4],params['vol'][-4:])
            sys.exit()

#==============================
def spider_thresh_mask(vol,thresh,dilate,savemask):

5 Source : make_tilt_pair_file.py
with MIT License
from cianfrocco-lab

def checkConflicts(params):
        if not params['path']:
                print "\nWarning: no path specified\n"
        elif not os.path.exists(params['path']):
                print "\nError: path '%s' does not exist\n" % params['path']
                sys.exit()
	if os.path.exists(params['output']):
		print "\nError: output file %s already exists. Exiting\n" %(params['output'])
		sys.exit()
	if not params['Text']:
                print "\nWarning: no tilted micrograph extension specified\n"
                sys.exit()
	if not params['Uext']:
                print "\nWarning: no untilted micrograph extension specified\n"
                sys.exit()

#==================
def start(param):

5 Source : __main__.py
with Apache License 2.0
from comtihon

def main(args=None):
    try:
        arguments = docopt(__doc__, argv=args, version=APPVSN)
    except DocoptExit as usage:
        print(usage)
        sys.exit(1)
    path = os.getcwd()
    logger.configure(arguments['--log-level'], not arguments['--no-color'])
    result = run_tests(path, arguments)
    if result:
        sys.exit(0)
    else:
        sys.exit(1)


def run_tests(path: str, arguments: dict):

5 Source : cronohub.py
with MIT License
from cronohub

def display_help(t: str):
    if t == 'source':
        plugin = load_from_plugin_folder(t, args.source_help)
        if not plugin:
            print('plugin %s not found' % args.source_help)
            sys.exit(1)
        plugin.SourcePlugin().help()
    else:
        plugin = load_from_plugin_folder(t, args.target_help)
        if not plugin:
            print('plugin %s not found' % args.target_help)
            sys.exit(1)
        plugin.TargetPlugin().help()
    sys.exit(0)


def main():

5 Source : __main__.py
with GNU General Public License v3.0
from cs50

def check_docker():
    """Check if Docker is installed and responding"""
    # Check if Docker installed
    if not shutil.which("docker"):
        sys.exit(_("Docker not installed"))

    # Check if Docker running
    try:
        subprocess.check_call(["docker", "info"], stderr=subprocess.DEVNULL,
                              stdout=subprocess.DEVNULL, timeout=10)

    except subprocess.CalledProcessError:
        sys.exit(_("Docker not running"))
    except subprocess.TimeoutExpired:
        sys.exit(_("Docker not responding"))


def container_info(container):

5 Source : db_load.py
with Apache License 2.0
from CSCfi

def validate_arguments(arguments):
    """Check that given arguments are valid."""
    if not Path(arguments.datafile).is_file():
        sys.exit(f"Could not find datafile: {arguments.datafile}")
    if not Path(arguments.metadata).is_file():
        sys.exit(f"Could not find metadata file: {arguments.metadata}")
    if not arguments.min_allele_count.isdigit():
        sys.exit(f"Minimum allele count --min_allele_count must be a positive integer, received: {arguments.min_allele_count}")


def parse_arguments(arguments):

5 Source : cli.py
with Apache License 2.0
from deeplearning4j

def handle():
    try:
        cli = CLI()
        sys.exit(cli.command_dispatcher())
    except KeyboardInterrupt:
        sys.exit()
    except Exception as e:
        click.echo(click.style("Error: ", fg='red', bold=True))
        traceback.print_exc()
        sys.exit()


if __name__ == '__main__':

5 Source : main.py
with MIT License
from edge-minato

def main() -> None:
    try:
        args()
        process()
    except PypjError as e:
        print(f"Error: {e}")
        sys.exit(1)
    except KeyboardInterrupt:
        print()
        print("Canceled.")
        sys.exit(1)
    except Exception:
        print(format_exc())
        print()
        print("If you are behind a proxy, try to set following environmental variables.")
        print("http_proxy, https_proxy, HTTP_PROXY, HTTPS_PROXY")
        print(f"Else, please report the issue to {GITHUB_URL}")
        sys.exit(1)

5 Source : run.py
with MIT License
from EmixamPP

def execute(trigger=False) -> NoReturn:
    """Apply all saved drivers

    Args:
        trigger: and try to trigger the ir emitter. Defaults to False.
    """
    driver_list = DriverSerializer.load_saved_drivers()
    if not driver_list:
        sys.exit(ExitCode.FAILURE)

    for driver in driver_list:
        exit_code = driver.run() if not trigger else driver.trigger_ir()

        exit_if_file_descriptor_error(exit_code, driver.device)
        if exit_code != ExitCode.SUCCESS:
            logging.critical("Bad driver for %s.", driver.device)
            sys.exit(exit_code)

    sys.exit(ExitCode.SUCCESS)

5 Source : arguments_checkers.py
with GNU General Public License v2.0
from fabiopipitone

def parse_lbi(lbi, allow_short_interval, multiprocess_enabled):
  try:
    number = re.search("\d+", lbi).group() if re.search("\d+", lbi) != None else None
    unit = re.search("[^\d]+", lbi).group() if re.search("[^\d]+", lbi) != None else None
    allowed_units = ['m', 'h', 'd', 'w', 'M', 'y'] if allow_short_interval else ['d', 'w', 'M', 'y']
    unit_in_seconds = {'m':60, 'h':3600, 'd':86400, 'w':604800 , 'M':2592000, 'y':31104000}
    if number == None or not number.isnumeric():
      sys.exit(wrap_red("--load_balance_interval option must begin with a number. Please check the --help to know how to properly set it"))
    elif unit == None or unit == '' or unit not in allowed_units:
      sys.exit(wrap_red(f"--load_balance_interval unit must be one of the following {allowed_units}. Please check the --help to know how to properly set it"))
    elif not multiprocess_enabled:
      sys.exit(wrap_red("Multiprocessing must be enabled (-em True) in order to set the --load_balance_interval"))
    else:
      return int(number) * unit_in_seconds[unit]
  except:
    sys.exit(wrap_red("Something in the combination of --load_balance_interval and --allow_short_interval you set is wrong. Please check the --help to know how to properly set them"))

def check_valid_lbi(starting_date, ending_date, lbi):

5 Source : bump_aea_version.py
with Apache License 2.0
from fetchai

def main() -> None:
    """Run the script."""
    repo = Repo(str(ROOT_DIR))
    if repo.is_dirty():
        logging.info(
            "Repository is dirty. Please clean it up before running this script."
        )
        sys.exit(1)

    arguments = parse_args()
    if arguments.only_check:
        sys.exit(only_check_bump_needed())

    return_code = bump(arguments)
    sys.exit(return_code)


if __name__ == "__main__":

5 Source : cli.py
with MIT License
from frostming

def import_class(import_string):
    try:
        module, classname = import_string.rsplit(".", 1)
        cls = getattr(importlib.import_module(module), classname)
    except ValueError:
        sys.exit("Please supply module.classname.")
    except ImportError:
        sys.exit("Cannot import module %s" % module)
    except AttributeError:
        sys.exit(f"Cannot find class {classname} in module {module}")
    else:
        return cls


def parse(args):

5 Source : args.py
with Apache License 2.0
from gardatech

def exit_on_bad_args(args: Namespace):

    if not os.path.isdir(args.suite):
        sys.exit(f"ERROR: suite directory '{args.suite}' doesn't exist")

    if not os.path.isdir(args.templates):
        sys.exit(f"ERROR in --templates: directory '{args.templates}' doesn't exist")

    template_path = os.path.join(args.templates, args.template_name)
    checked_path = none_on_bad_nonempty_file(template_path)
    if not checked_path:
        sys.exit(
            f"ERROR in --templates/--template-name: file '{template_path}'"
            + " is nonexistent, empty or not accessible"
        )


def post_process_args(args: Namespace):

5 Source : args.py
with Apache License 2.0
from gardatech

def exit_on_bad_args(args):

    if args.user_id   <   1:
        sys.exit(f"ERROR in --user-id: bad user id '{args.user_id}'")

    if args.engagement  <  1:
        sys.exit(f"ERROR in --engagement: bad engagement id '{args.engagement}'")

    if not os.path.isfile(args.results_file):
        sys.exit(f"ERROR in --results-file: file '{args.results_file}' doesn't exist")

    if os.path.getsize(args.results_file) == 0:
        sys.exit(f"ERROR in --results-file: file '{args.results_file}' is empty")

5 Source : gunc.py
with GNU General Public License v3.0
from grp-bork

def start_checks():
    """Checks if tool dependencies are available."""
    if not external_tools.check_if_tool_exists("diamond"):
        sys.exit("[ERROR] Diamond 2.0.4 not found..")
    else:
        diamond_ver = external_tools.check_diamond_version()
        if diamond_ver != "2.0.4":
            sys.exit(f"[ERROR] Diamond version is {diamond_ver}, not 2.0.4")
    if not external_tools.check_if_tool_exists("prodigal"):
        sys.exit("[ERROR] Prodigal not found..")
    if not external_tools.check_if_tool_exists("grep"):
        sys.exit("[ERROR] grep not found..")
    if not external_tools.check_if_tool_exists("zcat"):
        sys.exit("[ERROR] zcat not found..")


def get_files_in_dir_with_suffix(directory, suffix):

5 Source : cli.py
with MIT License
from hassio-addons

def git_askpass():
    """
    Git credentials helper.

    Short & sweet script for use with git clone and fetch credentials.
    Requires GIT_USERNAME and GIT_PASSWORD environment variables,
    intended to be called by Git via GIT_ASKPASS.
    """
    if argv[1] == "Username for 'https://github.com': ":
        print(environ["GIT_USERNAME"])
        sys.exit()

    if argv[1] == "Password for 'https://" "%(GIT_USERNAME)[email protected]': " % environ:
        print(environ["GIT_PASSWORD"])
        sys.exit()

    sys.exit(1)

5 Source : main.py
with Apache License 2.0
from HathorNetwork

def main():
    try:
        sys.exit(CliManager().execute_from_command_line())
    except KeyboardInterrupt:
        logger.warn('Aborting and exiting...')
        sys.exit(1)
    except Exception:
        logger.exception('Uncaught exception:')
        sys.exit(2)


if __name__ == '__main__':

5 Source : nbextensions.py
with BSD 3-Clause "New" or "Revised" License
from holzschu

    def start(self):
        if not self.extra_args:
            sys.exit('Please specify an nbextension to uninstall')
        elif len(self.extra_args) > 1:
            sys.exit("Only one nbextension allowed at a time. "
                     "Call multiple times to uninstall multiple extensions.")
        elif (self.user or self.sys_prefix or self.system or self.prefix
              or self.nbextensions_dir):
            # The user has specified a location from which to uninstall.
            try:
                self.uninstall_extension()
            except ArgumentConflict as e:
                sys.exit(str(e))
        else:
            # Uninstall wherever it is.
            self.find_uninstall_extension()


class ToggleNBExtensionApp(BaseExtensionApp):

5 Source : sqlrestore.py
with Apache License 2.0
from IBM

def validate_input():
    if(options.username is None or options.password is None or options.host is None or
       options.db is None or options.newname is None):
        print("Invalid input, use -h switch for help")
        sys.exit(2)
    if(options.start is None and options.end is not None):
        print("Start date required if end date is defined")
        sys.exit(2)
    if(options.start is not None and options.end is None):
        print("End date required if start date is defined")
        sys.exit(2)
    if(options.mode not in ['test','production','IA']):
        print("Mode invalid, please use: test, production or IA")
        sys.exit(2)

def find_db():

5 Source : vmwaretestrestore.py
with Apache License 2.0
from IBM

def validate_input():
    if(options.username is None or options.password is None or options.host is None or
       options.vms is None):
        print("Invalid input, use -h switch for help")
        sys.exit(2)
    if(options.start is None and options.end is not None):
        print("Start date required if end date is defined")
        sys.exit(2)
    if(options.start is not None and options.end is None):
        print("End date required if start date is defined")
        sys.exit(2)

def build_vm_source():

5 Source : vmware_inventory.py
with Apache License 2.0
from IBM

def validate_input():
  if options.username is None or options.password is None or options.hostname is None:
    print("ERROR: use -h switch for help")
    sys.exit(2)
    
  if options.type != "host" and options.type != "cluster":
    print("ERROR: you must specify a type of either host or cluster")
    sys.exit(2)
    
  if ("https" in options.hostname):
    print("ERROR: you need to specify a host IP or DNS and not a URL")
    sys.exit(2)
    
def debug_msg(function_name, message):

5 Source : dbconnection.py
with Apache License 2.0
from janw

    def handle(self, *args, **options):

        # If connection is already up: exit.
        if connection.connection is not None:
            sys.exit(0)

        # Wait for a proper database connection
        logger.info("Waiting for Database connection.")
        retry_count = 30
        while retry_count > 0:
            try:
                connection.ensure_connection()
            except Exception:
                time.sleep(1)
                retry_count -= 1
            else:
                sys.exit(0)
        logger.error(f"Database did not become available in {retry_count} seconds.")
        sys.exit(1)

5 Source : SecurityMigrator.py
with Apache License 2.0
from jfrog

def setup_art_access(artifactory_url, username, password, repo, ignore_cert):
    art_access = ArtifactoryDockerAccess(url=artifactory_url, username=username,
                                   password=password, repo=repo, ignore_cert=ignore_cert)
    if not art_access.is_valid():
        sys.exit("The provided Artifactory URL or credentials do not appear valid.")
    if not art_access.is_valid_version():
        sys.exit("The provided Artifactory instance is version %s but only 4.4.3+ is supported." %
                 art_access.get_version())
    if not art_access.is_valid_docker_repo():
        sys.exit("The repo %s does not appear to be a valid V2 Docker repository." % args.repo)

    return art_access

def setup_logging(level):

5 Source : oxford.py
with GNU General Public License v3.0
from kenkellner

    def check_fulltext(self):
        if self.soup.find('div',{'data-widgetname':'ArticleFulltext'}) == None:
            sys.exit('Error: Can\'t access fulltext of article')
        elif self.soup.find('span',{'id':'UserHasAccess'}) \
                ['data-userhasaccess'] == 'False':        
            sys.exit('Error: Can\'t access fulltext of article')
        elif self.soup.find('div',class_='PdfOnlyLink') != None:
            sys.exit('Error: Can\'t access fulltext of article')
        else:
            return(True)
    
    def get_doi(self):

5 Source : wiley.py
with GNU General Public License v3.0
from kenkellner

    def check_fulltext(self):
        full = self.soup.find('section',class_='article-section__full')
        try:
            if full != None:
                if full.find('div',class_='article-section__content') \
                    .text == '\n\xa0\n':
                    sys.exit('Error: Can\'t access fulltext of article')
                else:
                    return(True)
            else:
                sys.exit('Error: Can\'t access fulltext of article')
        except:
            sys.exit('Error: Can\'t access fulltext of article')
 
    def get_doi(self):

5 Source : Database_mysql.py
with GNU General Public License v3.0
from liode1s

    def conn_mysql(self):
        self.data = self.conn_list
        try:
            db = pymysql.connect(host = self.data[2], user = self.data[0], passwd = self.data[1], port = self.data[3])
            cursor = db.cursor()
            return cursor
        except Exception as e:
            self.col.printRed(e[1] + "\n")
            if e[0] == 1045:
                self.col.printRed(u"用户名或密码错误!\n请检查你的用户名和密码是否正确!\n")
                sys.exit()
            elif e[0] == 2003:
                self.col.printRed(u"无法连接对方mysql服务!\n请检测你是否可以连接到对方网络,ip端口是否输入正确, 或者对方数据库不支持外链!\n")
                sys.exit()
            else:
                self.col.printBlue(u"未知错误!\n")
                sys.exit()

    def run_sql(self, command):

5 Source : affine_cipher.py
with Mozilla Public License 2.0
from ls1248659692

def checkKeys(keyA, keyB, mode):
    if keyA == 1 and mode == 'encrypt':
        sys.exit('The affine cipher becomes weak when key A is set to 1. Choose different key')
    if keyB == 0 and mode == 'encrypt':
        sys.exit('The affine cipher becomes weak when key A is set to 1. Choose different key')
    if keyA   <   0 or keyB  <  0 or keyB > len(SYMBOLS) - 1:
        sys.exit('Key A must be greater than 0 and key B must be between 0 and %s.' % (len(SYMBOLS) - 1))
    if cryptoMath.gcd(keyA, len(SYMBOLS)) != 1:
        sys.exit('Key A %s and the symbol set size %s are not relatively prime. Choose a different key.' % (keyA, len(SYMBOLS)))

def encryptMessage(key, message):

5 Source : dependencies.py
with BSD 3-Clause "New" or "Revised" License
from m1stadev

    def check_bin(self, binary):
        if shutil.which(binary) is None:
            sys.exit(f"[ERROR] '{binary}' is not installed on your system. Exiting.")

        if binary == 'futurerestore':
            fr_ver = subprocess.run((binary), stdout=subprocess.PIPE, universal_newlines=True).stdout
            if '-m1sta' not in fr_ver.splitlines()[1]:
                sys.exit(f"[ERROR] This futurerestore build cannot be used with Inferius. Exiting.")

        elif binary == 'irecovery':
            try:
                subprocess.check_call((binary, '-V'), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            except subprocess.CalledProcessError:
                sys.exit(f"[ERROR] Your irecovery version is too old. Exiting.")

5 Source : restore.py
with BSD 3-Clause "New" or "Revised" License
from m1stadev

    def send_component(self, file, component):
        if component == 'iBSS' and self.platform in (8960, 8015): #TODO: Reset device via pyusb rather than call an external binary.
            irecovery_reset = subprocess.run(('irecovery', '-f', file), stdout=subprocess.DEVNULL)
            if irecovery_reset.returncode != 0:
                sys.exit('[ERROR] Failed to reset device. Exiting.')

        irecovery = subprocess.run(('irecovery', '-f', file), stdout=subprocess.DEVNULL)
        if irecovery.returncode != 0:
            sys.exit(f"[ERROR] Failed to send '{component}'. Exiting.")

        if component == 'iBEC':
            if 8010   <  = self.platform  < = 8015:
                irecovery_jump = subprocess.run(('irecovery', '-c', 'go'), stdout=subprocess.DEVNULL)
                if irecovery_jump.returncode != 0:
                    sys.exit(f"[ERROR] Failed to boot '{component}'. Exiting.")

            time.sleep(3)

    def sign_component(self, file, output):

5 Source : ModuleProvider.py
with GNU General Public License v3.0
from mdawsonuk

def __check_plugin_folder() -> None:
    """
    Checks that the plugin folder exists. If not, it quits with the corresponding exit code
    """
    if not os.path.exists("plugins"):
        sys.exit(ExitCode.PluginDirectoryMissing)
    if not os.path.exists("plugins/initmodules"):
        sys.exit(ExitCode.EntryPointModulesNotLoaded)
    if not os.path.exists("plugins/modules"):
        sys.exit(ExitCode.ModuleDirectoryMissing)


def __load_init_modules() -> None:

5 Source : cli.py
with GNU Affero General Public License v3.0
from mkb79

def quickstart(ctx):
    """Entrypoint for the quickstart command"""
    try:
        sys.exit(ctx.forward(cmd_quickstart.cli))
    except click.Abort:
        logger.error("Aborted")
        sys.exit(1)
    except AudibleCliException as e:
        logger.error(e)
        sys.exit(2)
    except Exception:
        logger.exception("Uncaught Exception")
        sys.exit(3)


def main(*args, **kwargs):

5 Source : cli.py
with GNU Affero General Public License v3.0
from mkb79

def main(*args, **kwargs):
    try:
        sys.exit(cli(*args, **kwargs))
    except click.Abort:
        logger.error("Aborted")
        sys.exit(1)
    except AudibleCliException as e:
        logger.error(e)
        sys.exit(2)
    except Exception:
        logger.exception("Uncaught Exception")
        sys.exit(3)

5 Source : get_dashboard_token.py
with Mozilla Public License 2.0
from mosip

def main():
    args, parser =  args_parse()
    if args.service_account not in SERVICE_ACCOUNTS:
        parser.print_help()
        sys.exit(1)
    try:
        token = get_dashboard_token(args.service_account, args.kubeconfig)
        fp = open(args.outfile, 'wt')
        fp.write(token)
        fp.write('\n')
        fp.close()
    except:
        formatted_lines = traceback.format_exc()
        print(formatted_lines)
        sys.exit(2)
    sys.exit(0)

if __name__=="__main__":

5 Source : tui.py
with MIT License
from mystor

def main(argv: Optional[List[str]] = None) -> None:
    args = build_parser().parse_args(argv)
    try:
        with Repository() as repo:
            inner_main(args, repo)
    except CalledProcessError as err:
        print(f"subprocess exited with non-zero status: {err.returncode}")
        sys.exit(1)
    except EditorError as err:
        print(f"editor error: {err}")
        sys.exit(1)
    except MergeConflict as err:
        print(f"merge conflict: {err}")
        sys.exit(1)
    except ValueError as err:
        print(f"invalid value: {err}")
        sys.exit(1)

5 Source : GUESSmyLT.py
with GNU General Public License v3.0
from NBISweden

def check_mode(mode):
    """
    checks if we are dealing with genome or transcriptome by looking at the provided option    
    """
    #check that the mode asked exists
    if not mode:
        print("Mode parameter (--mode) must be filled when no annotation provided (--annotation). Accepted value: genome or transcriptome.")
        sys.exit()
    elif mode.lower() in "genome" and mode.lower() not in "transcriptome":
        return "genome"
    elif mode.lower() in "transcriptome" and mode.lower() not in "genome" :
        print("Transcriptome mode is not yet implemented.")
        sys.exit()
        return "transcriptome"
    else:
        print("Unrecognized mode --mode "+mode+". Only   <  genome> or  < transcriptome> are valid mode.")
        sys.exit()

def check_reference(ref):

5 Source : common.py
with GNU Affero General Public License v3.0
from nccgroup

def error_and_exit(message, json=False, newline=False, error_text=True,
                   error_type=None):
    if json:
        stdout_json(dict(error=message, error_type=error_type))
        sys.exit(1)
    else:
        if newline:
            print()

        if error_text:
            sys.exit("Error: " + message)
        else:
            sys.exit(message)


def exception_and_exit(exc, **kwargs):

5 Source : sync.py
with Apache License 2.0
from neptune-ai

def verify_file(path):
    if not os.path.exists(path):
        click.echo("ERROR: File `{}` doesn't exist".format(path), err=True)
        sys.exit(1)

    if not os.path.isfile(path):
        click.echo("ERROR: `{}` is not a file".format(path), err=True)
        sys.exit(1)

    if not path.endswith(".ipynb"):
        click.echo("ERROR: '{}' is not a correct notebook file. Should end with '.ipynb'.".format(path), err=True)
        sys.exit(1)


def print_link_to_notebook(project, notebook_name, notebook_id):

5 Source : core.py
with MIT License
from nikhiljohn10

	def get_zone_id(self):
		try:
			zones = self.dns.zones.get(params = {'name': self.zone_name})
			self.zone_id = zones[0]['id']
		except CloudFlare.exceptions.CloudFlareAPIError as err:
			sys.exit('/zones %d %s - api call failed' % (err, err))
		except Exception as e:
			sys.exit('/zones.get - %s - api call failed' % (err))

		if len(zones) == 0:
			sys.exit('/zones.get - %s - zone not found' % (self.zone_name))

		if len(zones) != 1:
			sys.exit('/zones.get - %s - api call returned %d items' % (self.zone_name, len(zones)))
		

	def get_record_id(self):

5 Source : cdk_construct.py
with Apache License 2.0
from nwcd-samples

def get_install_properties():
    config_file_path = f"{os.path.dirname(os.path.realpath(__file__))}/config.yml"
    try:
        config_parameters = yaml.load(open(config_file_path, 'r'), Loader=yaml.FullLoader) # nosec
    except ScannerError as err:
        print(f"{config_file_path} is not a valid YAML file. Verify syntax, {err}")
        sys.exit(1)
    except FileNotFoundError:
        print(f"{config_file_path} not found")
        sys.exit(1)
    if config_parameters:
        return config_parameters
    else:
        sys.exit("No parameters were specified.")


class SOCAInstall(cdk.Stack):

See More Examples