Python sys.argv() Examples

The following are 30 code examples of sys.argv(). 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: 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 #2
Source File: example_restart_python.py    From EDeN with MIT License 7 votes vote down vote up
def main():
    env = os.environ.copy()

    # in case the PYTHONHASHSEED was not set, set to 0 to denote
    # that hash randomization should be disabled and
    # restart python for the changes to take effect
    if 'PYTHONHASHSEED' not in env:
        env['PYTHONHASHSEED'] = "0"
        proc = subprocess.Popen([sys.executable] + sys.argv,
                                env=env)
        proc.communicate()
        exit(proc.returncode)

    # check if hash has been properly de-randomized in python 3
    # by comparing hash of magic tuple
    h = hash(eden.__magic__)
    assert h == eden.__magic_py2hash__ or h == eden.__magic_py3hash__, 'Unexpected hash value: "{}". Please check if python 3 hash normalization is disabled by setting shell variable PYTHONHASHSEED=0.'.format(h)

    # run program and exit
    print("This is the magic python hash restart script.")
    exit(0) 
Example #3
Source File: weather-icons.py    From unicorn-hat-hd with MIT License 6 votes vote down vote up
def weather_icons():
    try:

        if argv[1] == 'loop':

            loop()

        elif argv[1] in os.listdir(folder_path):

            print('Drawing Image: {}'.format(argv[1]))

            img = Image.open(folder_path + argv[1])

            draw_animation(img)
            unicorn.off()

        else:
            help()

    except IndexError:
        help() 
Example #4
Source File: __main__.py    From vergeml with MIT License 6 votes vote down vote up
def _forgive_wrong_option_order(argv):
    first_part = []
    second_part = []
    rest = copy(argv)

    while rest:
        arg = rest.pop(0)

        if arg.startswith("--"):
            argname = arg.lstrip("--")
            if "=" in argname:
                argname = argname.split("=")[0]
            is_vergeml_opt = bool(argname in _VERGEML_OPTION_NAMES)
            lst = (first_part if is_vergeml_opt else second_part)

            if arg.endswith("=") or not "=" in arg:
                if not rest:
                    # give up
                    second_part.append(arg)
                else:
                    lst.append(arg)
                    lst.append(rest.pop(0))
            else:
                lst.append(arg)

        else:
            second_part.append(arg)

    return first_part + second_part 
Example #5
Source File: batch.py    From aegea with Apache License 2.0 6 votes vote down vote up
def ensure_lambda_helper():
    awslambda = getattr(clients, "lambda")
    try:
        helper_desc = awslambda.get_function(FunctionName="aegea-dev-process_batch_event")
        logger.info("Using Batch helper Lambda %s", helper_desc["Configuration"]["FunctionArn"])
    except awslambda.exceptions.ResourceNotFoundException:
        logger.info("Batch helper Lambda not found, installing")
        import chalice.cli
        orig_argv = sys.argv
        orig_wd = os.getcwd()
        try:
            os.chdir(os.path.join(os.path.dirname(__file__), "batch_events_lambda"))
            sys.argv = ["chalice", "deploy", "--no-autogen-policy"]
            chalice.cli.main()
        except SystemExit:
            pass
        finally:
            os.chdir(orig_wd)
            sys.argv = orig_argv 
Example #6
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 #7
Source File: tnode.py    From iSDX with Apache License 2.0 6 votes vote down vote up
def main (argv):
    global host, hosts, tests
    
    if len(argv) == 3:      # tnode.py torch.cfg hostname
        cfile = argv[1]
        host = argv[2]
    else:
        print 'usage: tnode torch.cfg hostname'
        exit()
    
    try:
        config = tlib.parser(cfile)
        hosts = config.hosts
        bgprouters = config.bgprouters
    except Exception, e:
        print 'Bad configuration: ' + repr(e)
        exit() 
Example #8
Source File: LPHK.py    From LPHK with GNU General Public License v3.0 6 votes vote down vote up
def shutdown():
    if lp_events.timer != None:
        lp_events.timer.cancel()
    scripts.to_run = []
    for x in range(9):
        for y in range(9):
            if scripts.threads[x][y] != None:
                scripts.threads[x][y].kill.set()
    if window.lp_connected:
        scripts.unbind_all()
        lp_events.timer.cancel()
        launchpad_connector.disconnect(lp)
        window.lp_connected = False
    logger.stop()
    if window.restart:
        if IS_EXE:
            os.startfile(sys.argv[0])
        else:
            os.execv(sys.executable, ["\"" + sys.executable + "\""] + sys.argv)
    sys.exit("[LPHK] Shutting down...") 
Example #9
Source File: create_metadata.py    From CAMISIM with Apache License 2.0 6 votes vote down vote up
def parse_options():
    """
    parse command line options
    """
    parser = argparse.ArgumentParser()

    helptext="Root path of input run for which metadata should be created, should contain metadata.tsv and genome_to_id.tsv"
    parser.add_argument("-i", "--input-run", type=str, help=helptext)

    helptext="output file to write metadata to"
    parser.add_argument("-o", "--output", type=str, help=helptext)
    
    helptext="Name of the data set"
    parser.add_argument("-n", "--name", type=str, help=helptext)

    if not len(sys.argv) > 1:
        parser.print_help()
        return None
    args = parser.parse_args()

    return args 
Example #10
Source File: __main__.py    From spleeter with MIT License 6 votes vote down vote up
def main(argv):
    """ Spleeter runner. Parse provided command line arguments
    and run entrypoint for required command (either train,
    evaluate or separate).

    :param argv: Provided command line arguments.
    """
    try:
        parser = create_argument_parser()
        arguments = parser.parse_args(argv[1:])
        enable_logging()
        if arguments.verbose:
            enable_tensorflow_logging()
        if arguments.command == 'separate':
            from .commands.separate import entrypoint
        elif arguments.command == 'train':
            from .commands.train import entrypoint
        elif arguments.command == 'evaluate':
            from .commands.evaluate import entrypoint
        params = load_configuration(arguments.configuration)
        entrypoint(arguments, params)
    except SpleeterError as e:
        get_logger().error(e) 
Example #11
Source File: __main__.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def main(args=None):
    """The main routine."""
    if args is None:
        args = sys.argv[1:]

    print("The modules containing models are: ")
    for num, module in modules.items():
        print(str(num) + ". " + module[MODULE_NAME])
    choice = int(
                input("Enter module number to view avialable models: "))
    modules[choice][MODULE_MAIN]() 
Example #12
Source File: utils.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def read_props(model_nm):
    """
    A prop file to read must be our first arg, if it exists.
    """
    if len(sys.argv) > 1:
        poss_props = sys.argv[1]
        if not poss_props.startswith('-'):  # not a property but a prop file
            return prop_args.read_props(model_nm, poss_props)

    return None 
Example #13
Source File: prop_args2.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def overwrite_props_from_cl(self):
        prop_nm = None
        for arg in sys.argv:
            # the first arg (-prop) names the property
            if arg.startswith(SWITCH):
                prop_nm = arg.lstrip(SWITCH)
            # the second arg is the property value
            if prop_nm is not None:
                self.props[prop_nm].val = arg
                prop_nm = None 
Example #14
Source File: prop_args.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, model_nm, logfile=None, props=None,
                 loglevel=logging.INFO):
        self.model_nm = model_nm
        self.graph = nx.Graph()
        if props is None:
            self.props = {}
        else:
            self.props = props
            logfile = self.get("log_fname")
        self.logger = Logger(self, model_name=model_nm,logfile=logfile)
        self.graph.add_edge(self, self.logger)
        self["OS"] = platform.system()
        self["model"] = model_nm
        # process command line args and set them as properties:
        prop_nm = None
        for arg in sys.argv:
            # the first arg (-prop) names the property
            if arg.startswith(SWITCH):
                prop_nm = arg.lstrip(SWITCH)
            # the second arg is the property value
            elif prop_nm is not None:
                self[prop_nm] = arg
                prop_nm = None 
Example #15
Source File: manage.py    From django-rest-polymorphic with MIT License 5 votes vote down vote up
def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv) 
Example #16
Source File: remap.py    From svviz with MIT License 5 votes vote down vote up
def main():
    pass
    # genomeFastaPath = sys.argv[1]
    # genome = pyfaidx.Fasta(genomeFastaPath, as_raw=True)

    # bamPath = sys.argv[2]
    # bam = pysam.Samfile(bamPath, "rb")

    # eventType = sys.argv[3]

    # if eventType.lower().startswith("del"):
    #     if len(sys.argv) == 4:
    #         chrom, start, end = "chr1", 72766323, 72811840
    #     else:
    #         chrom = sys.argv[4]
    #         start = int(sys.argv[5])
    #         end = int(sys.argv[6])
    #     minmapq = 30

    #     variant = StructuralVariants.Deletion.from_breakpoints(chrom, start-1, end-1, extraSpace, genome)

    # elif eventType.lower().startswith("ins"):
    #     if len(sys.argv) == 4:
    #         chrom, pos, seq = "chr3", 20090540, L1SEQ
    #     else:
    #         chrom = sys.argv[4]
    #         pos = int(sys.argv[5])
    #         seq = int(sys.argv[6])
    #     minmapq = -1
    #     variant = StructuralVariants.Insertion(Locus(chrom, pos, pos, "+"), reverseComp(seq), extraSpace, genome) 
Example #17
Source File: app.py    From svviz with MIT License 5 votes vote down vote up
def main():
    # entry point for shell script
    run(sys.argv) 
Example #18
Source File: runTests.py    From svviz with MIT License 5 votes vote down vote up
def main():
    # don't ask me why I rolled my own regression testing code instead of using one of the 
    # gazillion existing frameworks...

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--reference", help="path for hg19 reference fasta; must be defined here or "
        "using the environmental variable SVVIZ_HG19_FASTA")

    parser.add_argument("mode", help="run|reset")
    parser.add_argument("which", nargs="*", help="which analyses to run (default all)")

    args = parser.parse_args()

    print(args.which)

    # if len(sys.argv) < 2:
    #     print USAGE
    #     return 

    if args.mode == "run":
        if getHG19Ref(args.reference) is None:
            parser.print_help()
            print("ERROR: Must provide path for hg19 reference fasta")
            sys.exit(1)
        run(args.which)
    elif args.mode == "reset":
        reset()
    else:
        parser.print_help() 
Example #19
Source File: cli.py    From mutatest with MIT License 5 votes vote down vote up
def cli_main() -> None:
    """Entry point to run CLI args and execute main function."""
    # Run a quick check at the beginning in case of later OS errors.
    cache.check_cache_invalidation_mode()
    args = cli_args(sys.argv[1:])
    main(args) 
Example #20
Source File: collector.py    From incubator-spot with Apache License 2.0 5 votes vote down vote up
def _parse_args():
    '''
        Parse command-line options found in 'args' (default: sys.argv[1:]).

    :returns: On success, a namedtuple of Values instances.
    '''
    parser   = ArgumentParser('Distributed Collector Daemon of Apache Spot', epilog='END')
    required = parser.add_argument_group('mandatory arguments')

    # .................................state optional arguments
    parser.add_argument('-c', '--config-file',
        default='ingest_conf.json',
        type=file,
        help='path of configuration file',
        metavar='')

    parser.add_argument('-l', '--log-level',
        default='INFO',
        help='determine the level of the logger',
        metavar='')

    parser.add_argument('--skip-conversion',
        action='store_true',
        default=False,
        help='no transformation will be applied to the data; useful for importing CSV files')

    # .................................state mandatory arguments
    required.add_argument('--topic',
        required=True,
        help='name of topic where the messages will be published')

    required.add_argument('-t', '--type',
        choices=pipelines.__all__,
        required=True,
        help='type of data that will be collected')

    return parser.parse_args() 
Example #21
Source File: spot_conf_migration.py    From incubator-spot with Apache License 2.0 5 votes vote down vote up
def main():

    if len(sys.argv[1:]) < 2:
        print "Please provide paths to: old_spot.conf , new_spot.conf"
        sys.exit(1)
        
    old_conf_file = sys.argv[1]
    new_conf_file = sys.argv[2]

    log = util.get_logger('SPOT.MIGRATE.CONF')

    old_path = os.path.dirname(os.path.realpath(old_conf_file))

    # create backup for the current configuration file.
    log.info("Create a backup of /etc/spot.conf before changing it") 
    util.execute_cmd('sudo cp {0} {1}/spot.conf.bkp_0_9'.format(old_conf_file, old_path),log)

    # create configuration objects.
    old_config = ConfigParser.ConfigParser()
    current_config = ConfigParser.ConfigParser()
    new_config = ConfigParser.ConfigParser()
    
    old_config.readfp(SecHead(open(old_conf_file)))
    current_config.readfp(SecHead(open(new_conf_file)))

    # create the new conf file.
    new_config.add_section('conf')
    for (k,v) in current_config.items("conf"):      
        if old_config.has_option('conf',k):
            new_config.set('conf',k, old_config.get('conf',k))
        else:
            new_config.set('conf',k,v)    
   
    new_path = os.path.dirname(os.path.realpath(new_conf_file)) 
    updated_conf_file = '{0}/spot.conf.new'.format(new_path)
    log.info("Generating merged configuration file in {0}".format(updated_conf_file)) 
    formatter(updated_conf_file,new_config)

    log.info("Updating original spot.conf with new and migrated variables and values") 
    util.execute_cmd('sudo cp {0} {1}/spot.conf'.format(updated_conf_file, old_path),log)
    util.execute_cmd('sudo chmod 0755 {0}/spot.conf'.format(old_path),log) 
Example #22
Source File: argv_args.py    From clikit with MIT License 5 votes vote down vote up
def __init__(self, argv=None):  # type: (Optional[List[str]]) -> None
        if argv is None:
            argv = list(sys.argv)

        argv = argv[:]
        self._script_name = argv.pop(0)
        self._tokens = argv
        self._option_tokens = list(
            itertools.takewhile(lambda arg: arg != "--", self.tokens)
        ) 
Example #23
Source File: test_argv_args.py    From clikit with MIT License 5 votes vote down vote up
def argv():
    original_argv = sys.argv

    yield

    sys.argv = original_argv 
Example #24
Source File: test_argv_args.py    From clikit with MIT License 5 votes vote down vote up
def test_create(argv):
    sys.argv = ("console", "server", "add", "--port", "80", "localhost")
    args = ArgvArgs()

    assert args.script_name == "console"
    assert ["server", "add", "--port", "80", "localhost"] == args.tokens 
Example #25
Source File: test_argv_args.py    From clikit with MIT License 5 votes vote down vote up
def test_create_with_custom_tokens(argv):
    sys.argv = ("console", "server", "add", "localhost")
    args = ArgvArgs(["console", "server", "add", "--port", "80", "localhost"])

    assert args.script_name == "console"
    assert ["server", "add", "--port", "80", "localhost"] == args.tokens 
Example #26
Source File: __main__.py    From vergeml with MIT License 5 votes vote down vote up
def _parsebase(argv):
    """Parse until the second part of the command.
    """
    shortopts = 'vf:m:' # version, file, model
    longopts = ['version', 'file=', 'model=', 'samples-dir=', 'test-split=', 'val-split=',
                'cache-dir=', 'random-seed=', 'trainings-dir=', 'project-dir=',
                'cache=', 'device=', 'device-memory=']

    args, rest = getopt.getopt(argv, shortopts, longopts)

    args = dict(args)
    # don't match prefix
    for opt in map(lambda s: s.rstrip("="), longopts):
        # pylint: disable=W0640
        if ''f'--{opt}' in args and not any(map(lambda a: a.startswith('--' + opt), argv)):
            # find the key that does not match
            keys = map(lambda a: a.split("=")[0].lstrip("-"), argv)
            keys = list(filter(lambda k: k in opt, keys))
            if keys:
                raise getopt.GetoptError('Invalid key', opt='--' + keys[0])
            else:
                raise getopt.GetoptError('Invalid key')

    # convert from short to long names
    for sht, lng in (('-v', '--version'), ('-m', '--model'), ('-f', '--file')):
        if sht in args:
            args[lng] = args[sht]
            del args[sht]

    args = {k.strip('-'):v for k, v in args.items()}

    return args, rest 
Example #27
Source File: util.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, msg='', include_doc=False):
        if msg is None:
            msg = ''
        self.msg = msg
        if include_doc:
            self.msg += '\n' + __doc__ % (sys.argv[0], ) 
Example #28
Source File: util.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def get_tempdir():
    """Create a directory for ourselves in the system tempdir."""
    tempdir = config.CONFIG.parser.get('tempdir', None)
    if tempdir:
        if '<timestamp>' in tempdir:
            tempdir = tempdir.replace('<timestamp>', time.strftime('%Y-%m-%d-%H%M'))
    else:
        script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        tempdir = os.path.join(tempfile.gettempdir(), script_name)
    if not os.path.exists(tempdir):
        os.makedirs(tempdir)
    return tempdir 
Example #29
Source File: config.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, defaults, args):
        script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        self.defaults = defaults
        self.dir = self.__find_config_dir(script_name)
        self.parser = self.__init_configparser(script_name)
        global DEBUG
        DEBUG = self.parser.getboolean('debug', DEBUG) or args.debug
        global VERBOSE
        VERBOSE = self.parser.getboolean('verbose', VERBOSE) or args.verbose
        global VERIFY_SSL
        VERIFY_SSL = self.parser.getboolean('verify_ssl', VERIFY_SSL)
        global UNICODE
        UNICODE = self.parser.getboolean('unicode', UNICODE)
        if DEBUG:
            # Turn on some extras
            global SAVE_PLAYLIST_FILE
            SAVE_PLAYLIST_FILE = True 
Example #30
Source File: config.py    From mlbv with GNU General Public License v3.0 5 votes vote down vote up
def generate_config(username=None, password=None, servicename="MLB.tv"):
        """Creates config file from template + user prompts."""
        script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
        # use the script name minus any extension for the config directory
        config_dir = None
        config_dir = os.path.join(Config.config_dir_roots[1], script_name)
        if not os.path.exists(config_dir):
            print("Creating config directory: {}".format(config_dir))
            os.makedirs(config_dir)
        config_file = os.path.join(config_dir, 'config')
        if os.path.exists(config_file):
            print("Aborting: The config file already exists at '{}'".format(config_file))
            return False

        # copy the template config file
        print("Generating basic config file at: {}".format(config_dir))
        current_dir = os.path.dirname(inspect.getfile(inspect.currentframe()))
        template_config_path = os.path.abspath(os.path.join(current_dir, '../../..', 'config.template'))
        if not os.path.exists(template_config_path):
            print("Could not find template config file [expected at: {}]".format(template_config_path))
            return False

        if username is None:
            username = input('Enter {} username: '.format(servicename))
        if password is None:
            password = input('Enter {} password: '.format(servicename))

        with open(template_config_path, 'r') as infile, open(config_file, 'w') as outfile:
            for line in infile:
                if line.startswith('# username='):
                    outfile.write("username={}\n".format(username))
                elif line.startswith('# password='):
                    outfile.write("password={}\n".format(password))
                else:
                    outfile.write(line)
        print("Finished creating config file: {}".format(config_file))
        print("You may want to edit it now to set up favourites, etc.")
        return True