>>> make_cmd_invocation('path/program', ['arg1', 'arg2'], {'darg': 4})
    ['./giotto-cmd', '/path/program/arg1/arg2/', '--darg=4']
4431
def make_cmd_invocation(invocation, args, kwargs):
    
    if not invocation.endswith('/'):
        invocation += '/'
    if not invocation.startswith('/'):
        invocation = '/' + invocation

    cmd = invocation

    for arg in args:
        cmd += str(arg) + "/"

    rendered_kwargs = []
    for k, v in kwargs.items():
        rendered_kwargs.append("--%s=%s" % (k,v))
    
    return ['./giotto-cmd', cmd] + rendered_kwargs
483775
def emit_path_arg(keywordstr, arg, fd, indent, max_line_len, line_len, eol):
    """"""

    quote = '"'

    arg = escape_str(arg)

    if not(need_new_line(max_line_len, line_len, arg)):
        fd.write(" " + quote + arg + quote)
        return False

    ## FIXME: we should split the path on '/' and '[]' into multiple lines
    ## and then print each line

    num_chars = max_line_len - line_len
    if num_chars <= 0:
        # really small max_line_len; we give up
        fd.write(" " + quote + arg + quote)
        return False

    while num_chars > 2 and arg[num_chars - 1:num_chars].isalnum():
        num_chars -= 1
    fd.write(" " + quote + arg[:num_chars] + quote)
    arg = arg[num_chars:]
    keyword_cont = ((len(keywordstr) - 1) * ' ') + '+'
    while arg != '':
        line_len = len(
            "%s%s %s%s%s%s" % (indent, keyword_cont, quote, arg, quote, eol))
        num_chars = len(arg) - (line_len - max_line_len)
        while num_chars > 2 and arg[num_chars - 1:num_chars].isalnum():
            num_chars -= 1
        fd.write('\n' + indent + keyword_cont + " " +
                 quote + arg[:num_chars] + quote)
        arg = arg[num_chars:]
903375
def execute_command(cmd, **kwargs):
    
    cmd_dict = {
        c: 'flask_philo.commands_flask_philo.' + c for c
            in dir(commands_flask_philo) if not c.startswith('_') and c != 'os'  # noqa
    }

    # loading specific app commands
    try:
        import console_commands
        for cm in console_commands.__all__:
            if not cm.startswith('_'):
                cmd_dict[cm] = 'console_commands.' + cm
    except Exception:
        pass

    if cmd not in cmd_dict:
        raise ConfigurationError('command {} does not exists'.format(cmd))
    cmd_module = importlib.import_module(cmd_dict[cmd])
    kwargs['app'] = app
    cmd_module.run(**kwargs)
644604
def cmd2args(cmd):
    
    if isinstance(cmd, str):
        return cmd if win32 else shlex.split(cmd)
    return cmd
38912
def _add_two_argument_command(self, command, arg1, arg2):
        """"""
        self.lines.append("{} {} {}".format(command, arg1, arg2))
349585
def main(args=None):
    
    parser = ArgumentParser(
        prog='baseline',
        description=DESCRIPTION)

    parser.add_argument(
        'path', nargs='*',
        help='module or directory path')

    parser.add_argument(
        '--movepath', help='location to move script updates')

    parser.add_argument(
        '-w', '--walk', action='store_true',
        help='recursively walk directories')

    args = parser.parse_args(args)

    paths = args.path or ['.']

    paths = [path for pattern in paths for path in glob(pattern)]

    if args.walk:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            for root, _dirs, files in os.walk(dirpath):
                paths += (os.path.join(root, filename) for filename in files)
    else:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            paths += (os.path.join(dirpath, pth) for pth in os.listdir(dirpath))

    update_paths = [
        os.path.relpath(p) for p in paths if p.lower().endswith(UPDATE_EXT)]

    exitcode = 0

    if update_paths:
        script_paths = [pth[:-len(UPDATE_EXT)] + '.py' for pth in update_paths]

        print('Found updates for:')
        for path in script_paths:
            print('  ' + path)
        print()

        if not args.movepath:
            try:
                input('Hit [ENTER] to update, [Ctrl-C] to cancel ')
            except KeyboardInterrupt:
                print()
                print('Update canceled.')
                exitcode = 1
            else:
                print()

        if exitcode == 0:
            for script_path, update_path in zip(script_paths, update_paths):
                if args.movepath:
                    script_path = os.path.join(args.movepath, script_path)
                    if update_path.startswith('..'):
                        raise RuntimeError(
                            'destination outside of move path: ' + script_path)
                    script_dirpath = os.path.dirname(script_path)
                    if not os.path.isdir(script_dirpath):
                        os.makedirs(script_dirpath)
                with open(update_path) as update:
                    new_content = update.read()
                with open(script_path, 'w') as script:
                    script.write(new_content)
                os.remove(update_path)
                print(update_path + ' -> ' + script_path)

    return exitcode
1275820
def main(prog_args=None):
    
    if prog_args is None:
        prog_args = sys.argv

    parser = optparse.OptionParser()
    parser.usage = """Usage: %[prog] [options] [<path>]"""
    parser.add_option("-t", "--test-program", dest="test_program",
        default="nose", help="specifies the test-program to use. Valid values"
        " include `nose` (or `nosetests`), `django`, `py` (for `py.test`), "
        '`symfony`, `jelix` `phpunit` and `tox`')
    parser.add_option("-d", "--debug", dest="debug", action="store_true",
        default=False)
    parser.add_option('-s', '--size-max', dest='size_max', default=25,
        type="int", help="Sets the maximum size (in MB) of files.")
    parser.add_option('--custom-args', dest='custom_args', default='',
        type="str",
        help="Defines custom arguments to pass after the test program command")
    parser.add_option('--ignore-dirs', dest='ignore_dirs', default='',
        type="str",
        help="Defines directories to ignore.  Use a comma-separated list.")
    parser.add_option('-y', '--quiet', dest='quiet', action="store_true",
        default=False,
        help="Don't ask for any input.")

    opt, args = parser.parse_args(prog_args)

    if args[1:]:
        path = args[1]
    else:
        path = '.'


    try:
        watcher = Watcher(path, opt.test_program, opt.debug, opt.custom_args, 
            opt.ignore_dirs, opt.quiet)
        watcher_file_size = watcher.file_sizes()
        if watcher_file_size > opt.size_max:
            message =  "It looks like the total file size (%dMb) is larger  than the `max size` option (%dMb).\nThis may slow down the file comparison process, and thus the daemon performances.\nDo you wish to continue? [y/N] " % (watcher_file_size, opt.size_max)

            if not opt.quiet and not ask(message):
                raise CancelDueToUserRequest('Ok, thx, bye...')

        print "Ready to watch file changes..."
        watcher.loop()
    except (KeyboardInterrupt, SystemExit):
        # Ignore when you exit via Crtl-C
        pass
    except Exception, msg:
        print msg

    print "Bye"
1356660
def convert_args(self, command, args):
		

		for wanted, arg in zip(command.argtypes(), args):
			wanted = wanted.type_
			if(wanted == "const"):
				try:
					yield to_int(arg)
				except:
					if(arg in self.processor.constants):
						yield self.processor.constants[arg]
					else:
						yield arg
			if(wanted == "register"):
				yield self.register_indices[arg]
239066
def add_cmd_handler(self, cmd, func):
        """"""
        len_args = len(inspect.getargspec(func)[0])

        def add_meta(f):
            def decorator(*args, **kwargs):
                f(*args, **kwargs)
            decorator.bytes_needed = len_args - 1  # exclude self
            decorator.__name__ = f.__name__
            return decorator
        func = add_meta(func)
        self._command_handlers[cmd] = func
561165
def _build_cmdargs(argv):
    
    parser = _build_arg_parser()
    namespace = parser.parse_args(argv[1:])

    cmdargs = vars(namespace)
    return cmdargs
337014
def command(self, init=False):
        """"""

        def wrapper(func):
            header = '\n'.join([s for s in (func.__doc__ or '').split('\n')
                                if not s.strip().startswith(':')])
            parser = self.parsers.add_parser(func.__name__, description=header)
            args, vargs, kw, defs, kwargs, kwdefs, anns = inspect.getfullargspec(func)
            defs = defs or []
            kwargs_ = dict(zip(args[-len(defs):], defs))
            docs = dict(PARAM_RE.findall(func.__doc__ or ""))

            def process_arg(name, *, value=..., **opts):
                argname = name.replace('_', '-').lower()
                arghelp = docs.get(vargs, '')
                if value is ...:
                    return parser.add_argument(argname, help=arghelp, **opts)

                if isinstance(value, bool):
                    if value:
                        return parser.add_argument(
                            "--no-" + argname, dest=name, action="store_false",
                            help="Disable %s" % (arghelp or name).lower())

                    return parser.add_argument(
                        "--" + argname, dest=name, action="store_true",
                        help="Enable %s" % (arghelp or name).lower())

                if isinstance(value, list):
                    return parser.add_argument(
                        "--" + argname, action="append", default=value, help=arghelp)

                return parser.add_argument(
                    "--" + argname, type=anns.get(name, type(value)),
                    default=value, help=arghelp + ' [%s]' % repr(value))

            if vargs:
                process_arg('*', nargs="*", metavar=vargs)

            for name, value in (kwdefs or {}).items():
                process_arg(name, value=value)

            for name in args:
                process_arg(name, value=kwargs_.get(name, ...))

            self.handlers[func.__name__] = func
            func.parser = parser
            return func

        if callable(init):
            init.__init__ = True
            return wrapper(init)

        def decorator(func):
            func.__init__ = bool(init)
            return wrapper(func)

        return decorator
787096
def arg(*args, **kwargs):
    
    def _arg(f):
        if not hasattr(f, '_subcommand_args'):
            f._subcommand_args = []
        f._subcommand_args.append((args, kwargs))
        return f
    return _arg
946863
def batch_arguments(arguments)
      batch = Batch.new do |x|
        arguments.each do |argument|
          # step: is the argument a subcommand?
          if subcommand?(argument)
            parser = subcommand(argument)
            # step: get the command and set the cursor to the parser
            x.cursor = parser.name
            # step: call the on_command block
            parser.on_command.call
          else
            # step: is this argument a parser argument
            parser = subcommand(x.cursor)
            if !is_switch?(argument)
              if x.previous
                x.global(argument)
              else
                x.add argument
              end
            elsif !parser.switch?(argument) and global_parser.switch?(argument)
              x.global(argument)
              x.previous = x.cursor
            else
              x.add argument
            end
          end
        end
      end
      yield batch if block_given?
      batch
    end
1043013
def run(self, argv):
        """"""
        command = argv[0]
        handlers = { 
            'clean': self.clean,
            'create': self.create,
            'disable': self.disable,
            'enable': self.enable,
            'list': self.list,
            'update': self.update,
        }
        handler = handlers.get(command, None)
        if handler is None:
            error("Unrecognized command: %s" % command, 2)
        handler(argv[1:])
710033
def build_argparser():
    """"""
    parser = ArgumentParser('Utility for managing MAR files')
    create_group = parser.add_argument_group("Create a MAR file")
    create_group.add_argument("-c", "--create", metavar="MARFILE", help="create MAR")
    create_group.add_argument("-V", "--productversion", dest="productversion",
                              help="product/version string")
    create_group.add_argument("-H", "--channel", dest="channel",
                              help="channel this MAR file is applicable to")
    create_group.add_argument("files", nargs=REMAINDER,
                              help="files to add to the MAR file")

    extract_group = parser.add_argument_group("Extract a MAR file")
    extract_group.add_argument("-x", "--extract", help="extract MAR", metavar="MARFILE")

    list_group = parser.add_argument_group("Print information on a MAR file")
    list_group.add_argument("-t", "--list", help="print out MAR contents",
                            metavar="MARFILE")
    list_group.add_argument("-T", "--list-detailed", metavar="MARFILE",
                            help="print out MAR contents including signatures")

    verify_group = parser.add_argument_group("Verify a MAR file")
    verify_group.add_argument("-v", "--verify", metavar="MARFILE",
                              help="verify the marfile")

    parser.add_argument("-j", "--bzip2", action="store_const", dest="compression",
                        const="bz2", help="compress/decompress members with BZ2")
    parser.add_argument("-J", "--xz", action="store_const", dest="compression",
                        const="xz", help="compress/decompress archive with XZ")
    parser.add_argument("--auto", action="store_const", dest="compression",
                        const="auto", help="automatically decompress contents")

    parser.add_argument("-k", "--keyfiles", dest="keyfiles", action='append',
                        help="sign/verify with given key(s)")
    parser.add_argument("-C", "--chdir", dest="chdir",
                        help="chdir to this directory before creating or "
                        "extracing; location of marfile isn't affected by "
                        "this option.")
    parser.add_argument("--verbose", dest="loglevel", action="store_const",
                        const=logging.DEBUG, default=logging.WARN,
                        help="increase logging verbosity")
    parser.add_argument('--version', action='version', version='mar version {}'.format(mardor.version_str))

    signing_group = parser.add_argument_group('Sign a MAR file')
    signing_group.add_argument('--hash', help='output hash for signing', choices=('sha1', 'sha384'))
    signing_group.add_argument('--asn1', help='format hash as an ASN1 DigestInfo block',
                               default=False, action='store_true')
    signing_group.add_argument('--add-signature', help='inject signature', nargs=3,
                               metavar=('input', 'output', 'signature'))

    return parser
674821
def main(argv=None):  # suppress(unused-function)
    
    argv = argv or sys.argv

    if "--" not in argv:
        sys.stderr.write("""Must specify command after '--'.\n""")
        return 1

    cmd_index = argv.index("--")
    args, cmd = (argv[1:cmd_index], argv[cmd_index + 1:])

    parser = argparse.ArgumentParser(description="""Cache results from jobs""")
    parser.add_argument("--dependencies",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of paths which, if more recent than the last time this job was invoked, will cause the job to be re-invoked.""")
    parser.add_argument("--output-files",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of expected output paths form this command, which, if they do not exist, will cause the job to be re-invoked.""")
    parser.add_argument("--stamp-directory",
                        metavar="DIRECTORY",
                        type=str,
                        help="""A directory to store cached results from this command. If a matching invocation is used and the files specified in --dependencies and --output-files are up-to-date, then the cached stdout, stderr and return code is used and the command is not run again.""")
    parser.add_argument("--use-hashes",
                        action="store_true",
                        help="""Use hash comparison in order to determine if dependencies have changed since the last invocation of the job. This method is slower, but can withstand files being copied or moved.""")
    namespace = parser.parse_args(args)
    stamp_directory = namespace.stamp_directory
    if namespace.use_hashes:
        method = jobstamp.HashMethod
    else:
        method = jobstamp.MTimeMethod

    result = jobstamp.run(_run_cmd,
                          cmd,
                          jobstamps_dependencies=namespace.dependencies,
                          jobstamps_output_files=namespace.output_files,
                          jobstamps_cache_output_directory=stamp_directory,
                          jobstamps_method=method)

    sys.stdout.write(result["stdout"].decode())
    sys.stderr.write(result["stderr"].decode())
    return result["code"]
1103249
def call(self, args, devnull=False):
        
        if self.debug:
            click.echo(subprocess.list2cmdline(args))
            click.confirm('Continue?', default=True, abort=True)
        try:
            kwargs = {}
            if devnull:
                # Pipe to /dev/null (or equivalent).
                kwargs['stderr'] = subprocess.STDOUT
                kwargs['stdout'] = self.FNULL
            ret_code = subprocess.call(args, **kwargs)
        except subprocess.CalledProcessError:
            return False
        return ret_code