Python sys.argv() Examples

The following are 30 code examples for showing how to use sys.argv(). 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module sys , or try the search function .

Example 1
Project: unicorn-hat-hd   Author: pimoroni   File: weather-icons.py    License: 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 2
Project: indras_net   Author: gcallah   File: prop_args.py    License: GNU General Public License v3.0 6 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 3
Project: mlbv   Author: kmac   File: config.py    License: GNU General Public License v3.0 6 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 4
Project: EDeN   Author: fabriziocosta   File: example_restart_python.py    License: MIT License 6 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 5
Project: aegea   Author: kislyuk   File: batch.py    License: 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
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: search.py    License: MIT License 6 votes vote down vote up
def main(wf):
    query = sys.argv[1]
    baseUrl = os.getenv('baseUrl')
    url = baseUrl + 'user?keyword=' + query
    try:
        result = web.get(url=url)
        result.raise_for_status()
        resp = result.text
        userList = json.loads(resp)
        if len(userList) > 0:
            for item in userList:
                title = item['title']
                subtitle = item['subTitle']
                icon = item['icon']
                userId = item['userId']
                copyText = item['copyText']
                qlurl = item['url']
                wf.add_item(title=title, subtitle=subtitle, icon=icon, largetext=title, copytext=copyText, quicklookurl=qlurl, arg=userId, valid=True)
        else:
            wf.add_item(title='找不到联系人…',subtitle='请重新输入')
    except IOError:
        wf.add_item(title='请先启动微信 & 登录…',subtitle='并确保安装微信小助手')

    wf.send_feedback() 
Example 7
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 8
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 9
Project: iSDX   Author: sdn-ixp   File: tnode.py    License: 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 10
Project: LPHK   Author: nimaid   File: LPHK.py    License: 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 11
Project: CAMISIM   Author: CAMI-challenge   File: create_metadata.py    License: 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 12
Project: spleeter   Author: deezer   File: __main__.py    License: 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 13
Project: facebook-discussion-tk   Author: internaut   File: analyze_noun_counts.py    License: MIT License 6 votes vote down vote up
def main():
    global output_file
    num_args = len(sys.argv)
    if num_args < 3:
        print("usage: %s <json-file-1> [json-file-2 ...] <output-csv-file>" % sys.argv[0], file=sys.stderr)
        exit(1)

    json_files = sys.argv[1:num_args - 1]
    output_file = sys.argv[num_args - 1]

    merged_json_data = {}
    for json_file in json_files:
        print("> reading JSON file '%s'..." % json_file)
        with open(json_file) as f:
            json_data = json.load(f)
            for label, data in json_data.items():
                if label not in merged_json_data:
                    merged_json_data[label] = data
                else:
                    merged_json_data[label]['data'].extend(data['data'])

    # pprint(merged_json_data)
    analyse(merged_json_data) 
Example 14
Project: indras_net   Author: gcallah   File: __main__.py    License: 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 15
Project: indras_net   Author: gcallah   File: utils.py    License: 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 16
Project: indras_net   Author: gcallah   File: prop_args2.py    License: 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 17
Project: django-rest-polymorphic   Author: apirobot   File: manage.py    License: 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 18
Project: svviz   Author: svviz   File: remap.py    License: 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 19
Project: svviz   Author: svviz   File: app.py    License: MIT License 5 votes vote down vote up
def main():
    # entry point for shell script
    run(sys.argv) 
Example 20
Project: svviz   Author: svviz   File: runTests.py    License: 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 21
Project: mutatest   Author: EvanKepner   File: cli.py    License: 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 22
Project: incubator-spot   Author: apache   File: collector.py    License: 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 23
Project: incubator-spot   Author: apache   File: spot_conf_migration.py    License: 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 24
Project: clikit   Author: sdispater   File: argv_args.py    License: 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 25
Project: clikit   Author: sdispater   File: test_argv_args.py    License: MIT License 5 votes vote down vote up
def argv():
    original_argv = sys.argv

    yield

    sys.argv = original_argv 
Example 26
Project: clikit   Author: sdispater   File: test_argv_args.py    License: 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 27
Project: clikit   Author: sdispater   File: test_argv_args.py    License: 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 28
Project: vergeml   Author: mme   File: __main__.py    License: 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 29
Project: vergeml   Author: mme   File: __main__.py    License: MIT License 5 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 30
Project: mlbv   Author: kmac   File: util.py    License: 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], )