Handle the forge subcommand
    :param args: Parsed command line arguments
    :return: None, output is written to console
770994
def run_forge(args):
    
    version = args.version
    commit_id = args.commit_id
    branch = args.branch

    try:
        print(Version(version, commit_id, branch))
    except DockerTagNamingException, de:
        print(de)
        sys.exit(1)
795886
def main(args=None):
    
    parser = argument_parser()
    args = parser.parse_args(args)

    # If 'func' isn't present, something is misconfigured above or no (positional) arg was given.
    if not hasattr(args, 'func'):
        args = parser.parse_args(['help'])  # show help

    # Convert argparse.Namespace into dict and clean it up.
    # We can then pass it directly to the helper function.
    kwargs = vars(args)

    # handle the '--dev' option
    if kwargs.pop('dev') or os.environ.get('QUILT_DEV_MODE', '').strip().lower() == 'true':
        # Enables CLI ctrl-c tracebacks, and whatever anyone else uses it for
        quilt._DEV_MODE = True
    else:
        # Disables CLI ctrl-c tracebacks, etc.
        quilt._DEV_MODE = False

    func = kwargs.pop('func')

    try:
        func(**kwargs)
        return 0
    except QuiltException as ex:
        print(ex.message, file=sys.stderr)
        return 1
    except requests.exceptions.ConnectionError as ex:
        print("Failed to connect: %s" % ex, file=sys.stderr)
        return 1
217445
def execute(cmd, cwd=None):
    
    try:
        lines = subprocess \
            .check_output(cmd, cwd=cwd, stderr=DEVNULL) \
            .splitlines()
    except subprocess.CalledProcessError:
        return None
    else:
        if lines:
            return decode(lines[0].strip())
        else:
            return None
110662
def main(args):
    
    try:
        import __main__
        parser = argparse.ArgumentParser(
            usage='%(prog)s [options] command\n\nVersion\n  %(prog)s version '
            + str(__version__),
            formatter_class=argparse.RawTextHelpFormatter)
        parser.add_argument('--version', action='version',
                            version='%(prog)s ' + str(__version__))
        build_subcommands_parser(parser, __main__)

        if len(args) <= 1:
            parser.print_help()
            return 1

        options = parser.parse_args(args[1:])
        # Filter out options with are not part of the function prototype.
        func_args = filter_subcommand_args(options.func, options)
        options.func(**func_args)

    except RuntimeError as err:
        LOGGER.error(err)
        return err.code
943333
def execute_command(self, cmd, params=None, callback=None, raw=False):
        '''
        
        '''
        def execute_with_callbacks(cmd, params=None, callback=None, raw=False):
            code, params = self.send_command(cmd, params, raw)
            if callback:
                callback(code, params)
            return code, params

        if self.daemon:
            t = Thread(target=execute_with_callbacks,
                    args=(cmd, ), kwargs={'params':params, 'callback':callback, 'raw':raw})
            t.daemon = True
            t.start()
        else:
            return execute_with_callbacks(cmd, params, callback, raw)
1292083
def build_subcommands_parser(parser, module):
    
    mdefs = module.__dict__
    keys = list(mdefs.keys())
    keys.sort()
    subparsers = parser.add_subparsers(help='sub-command help')
    for command in keys:
        if command.startswith('pub_'):
            func = module.__dict__[command]
            parser = subparsers.add_parser(command[4:], help=func.__doc__)
            parser.set_defaults(func=func)
            argspec = inspect.getargspec(func)
            flags = len(argspec.args)
            if argspec.defaults:
                flags = len(argspec.args) - len(argspec.defaults)
            if flags >= 1:
                for arg in argspec.args[:flags - 1]:
                    parser.add_argument(arg)
                parser.add_argument(argspec.args[flags - 1], nargs='*')
            short_opts = set([])
            for idx, arg in enumerate(argspec.args[flags:]):
                arg = arg.replace('_', '-')
                short_opt = arg[0]
                if not (arg.startswith('no') or (short_opt in short_opts)):
                    opts = ['-%s' % short_opt, '--%s' % arg]
                else:
                    opts = ['--%s' % arg]
                short_opts |= set([short_opt])
                if isinstance(argspec.defaults[idx], list):
                    parser.add_argument(*opts, action='append')
                elif isinstance(argspec.defaults[idx], dict):
                    parser.add_argument(*opts, type=json.loads)
                elif argspec.defaults[idx] is False:
                    parser.add_argument(*opts, action='store_true')
                elif argspec.defaults[idx] is not None:
                    parser.add_argument(*opts, default=argspec.defaults[idx])
                else:
                    parser.add_argument(*opts)
572263
def _handle_command(self, connection, sender, target, command, payload):
        
        try:
            # Find the handler
            handler = getattr(self, "cmd_{0}".format(command))
        except AttributeError:
            self.safe_send(connection, target, "Unknown command: %s",
                            command)
        else:
            try:
                logging.info("! Handling command: %s", command)
                handler(connection, sender, target, payload)
            except Exception as ex:
                logging.exception("Error calling command handler: %s", ex)
1142131
def execute_command(self, default_arg_list=None, **kwargs):
    
    _custom_func_arguments = set()

    if default_arg_list is None or len(default_arg_list) == 0:
      raise NoCommandException("No command passed, unable to continue")

    command_name = default_arg_list.pop(0)
    if command_name not in self._modules.keys():
      raise NoCommandException("No such command '{}' found, unable to continue".format(command_name))

    command = self._modules[command_name]
    entry_point = command["entry_point"]
    class_path = command["classpath"]
    metainfo = command["metainfo"]
    """:type metainfo ModuleMetaInfo"""

    try:
      args = metainfo.parse_default_arguments(default_arg_list)
      args.update(metainfo.parse_arguments(kwargs))

      f_args = entry_point.__code__.co_varnames[:entry_point.__code__.co_argcount]

      if len(f_args) - len(set(f_args) & _custom_func_arguments) != len(set(args.keys()) & set(f_args)):
        raise ArgumentException("Function \"{}\" from module {} doesn't implement all arguments in the signature".format(
          entry_point.__name__, class_path
        ))

      entry_point(**args)
    except ArgumentException as e:
      raise NoCommandException("Application arguments exception: {}\n".format(str(e)))
587483
def _execute_wk(*args, input=None):
    
    wk_args = (WK_PATH,) + args
    return subprocess.run(wk_args, input=input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
591097
def perform_command(self):
        
        if len(self.actual_arguments) < 1:
            return self.print_help()
        audio_file_path = self.actual_arguments[0]

        if not self.check_input_file(audio_file_path):
            return self.ERROR_EXIT_CODE

        try:
            prober = FFPROBEWrapper(rconf=self.rconf, logger=self.logger)
            dictionary = prober.read_properties(audio_file_path)
            for key in sorted(dictionary.keys()):
                self.print_generic(u"%s %s" % (key, dictionary[key]))
            return self.NO_ERROR_EXIT_CODE
        except FFPROBEPathError:
            self.print_error(u"Unable to call the ffprobe executable '%s'" % (self.rconf[RuntimeConfiguration.FFPROBE_PATH]))
            self.print_error(u"Make sure the path to ffprobe is correct")
        except (FFPROBEUnsupportedFormatError, FFPROBEParsingError):
            self.print_error(u"Cannot read properties of file '%s'" % (audio_file_path))
            self.print_error(u"Make sure the input file has a format supported by ffprobe")

        return self.ERROR_EXIT_CODE
1069210
def handle_args(args):
  
  parser = argparse.ArgumentParser()
  parser.add_argument("configpath", default=None, nargs="?",
                      help="/path/to/configs (always a directory; if omitted, all /configs are checked")
  parser.add_argument("--verbose", action="store_true", default=False)
  parsed_args = vars(parser.parse_args(args))
  # If a config path wasn't given, calculate it based on location of the script
  if parsed_args["configpath"] is None:
    script_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
    parsed_args["configpath"] = os.path.normpath("{}/{}".format(script_dir, CONFIGS_RELATIVE_PATH_FROM_SCRIPT_DIR))
  else:
    parsed_args["configpath"] = os.path.normpath(parsed_args["configpath"])
  # If the path is a directory, all good. if it's a file, find the directory the file is in and check that instead
  if os.path.isdir(parsed_args["configpath"]):
    parsed_args["configdir"] = parsed_args["configpath"]
  else:
    parsed_args["configdir"] = os.path.dirname(parsed_args["configpath"])
  return parsed_args
640262
def forward(*args, **kwargs):
        
        self, cmd = args[:2]

        # It's also possible to invoke another command which might or
        # might not have a callback.
        if not isinstance(cmd, Command):
            raise TypeError('Callback is not a command.')

        for param in self.params:
            if param not in kwargs:
                kwargs[param] = self.params[param]

        return self.invoke(cmd, **kwargs)
324329
def _execute(self, *args: str, **kwargs: Any) -> tuple:
        ''''''
        return self.execute(args=args, options=merge_dict(self.options, kwargs)).communicate()
93186
def handle(self, argv=None):
        

        desc = ('Zappa - Deploy Python applications to AWS Lambda'
                ' and API Gateway.\n')
        parser = argparse.ArgumentParser(description=desc)
        parser.add_argument(
            '-v', '--version', action='version',
            version=pkg_resources.get_distribution("zappa").version,
            help='Print the zappa version'
        )
        parser.add_argument(
            '--color', default='auto', choices=['auto','never','always']
        )

        env_parser = argparse.ArgumentParser(add_help=False)
        me_group = env_parser.add_mutually_exclusive_group()
        all_help = ('Execute this command for all of our defined '
                    'Zappa stages.')
        me_group.add_argument('--all', action='store_true', help=all_help)
        me_group.add_argument('stage_env', nargs='?')

        group = env_parser.add_argument_group()
        group.add_argument(
            '-a', '--app_function', help='The WSGI application function.'
        )
        group.add_argument(
            '-s', '--settings_file', help='The path to a Zappa settings file.'
        )
        group.add_argument(
            '-q', '--quiet', action='store_true', help='Silence all output.'
        )
        # https://github.com/Miserlou/Zappa/issues/407
        # Moved when 'template' command added.
        # Fuck Terraform.
        group.add_argument(
            '-j', '--json', action='store_true', help='Make the output of this command be machine readable.'
        )
        # https://github.com/Miserlou/Zappa/issues/891
        group.add_argument(
            '--disable_progress', action='store_true', help='Disable progress bars.'
        )

        ##
        # Certify
        ##
        subparsers = parser.add_subparsers(title='subcommands', dest='command')
        cert_parser = subparsers.add_parser(
            'certify', parents=[env_parser],
            help='Create and install SSL certificate'
        )
        cert_parser.add_argument(
            '--manual', action='store_true',
            help=("Gets new Let's Encrypt certificates, but prints them to console."
                "Does not update API Gateway domains.")
        )
        cert_parser.add_argument(
            '-y', '--yes', action='store_true', help='Auto confirm yes.'
        )

        ##
        # Deploy
        ##
        deploy_parser = subparsers.add_parser(
            'deploy', parents=[env_parser], help='Deploy application.'
        )
        deploy_parser.add_argument(
            '-z', '--zip', help='Deploy Lambda with specific local or S3 hosted zip package'
        )

        ##
        # Init
        ##
        init_parser = subparsers.add_parser('init', help='Initialize Zappa app.')

        ##
        # Package
        ##
        package_parser = subparsers.add_parser(
            'package', parents=[env_parser], help='Build the application zip package locally.'
        )
        package_parser.add_argument(
            '-o', '--output', help='Name of file to output the package to.'
        )

        ##
        # Template
        ##
        template_parser = subparsers.add_parser(
            'template', parents=[env_parser], help='Create a CloudFormation template for this API Gateway.'
        )
        template_parser.add_argument(
            '-l', '--lambda-arn', required=True, help='ARN of the Lambda function to template to.'
        )
        template_parser.add_argument(
            '-r', '--role-arn', required=True, help='ARN of the Role to template with.'
        )
        template_parser.add_argument(
            '-o', '--output', help='Name of file to output the template to.'
        )

        ##
        # Invocation
        ##
        invoke_parser = subparsers.add_parser(
            'invoke', parents=[env_parser],
            help='Invoke remote function.'
        )
        invoke_parser.add_argument(
            '--raw', action='store_true',
            help=('When invoking remotely, invoke this python as a string,'
                  ' not as a modular path.')
        )
        invoke_parser.add_argument(
            '--no-color', action='store_true',
            help=("Don't color the output")
        )
        invoke_parser.add_argument('command_rest')

        ##
        # Manage
        ##
        manage_parser = subparsers.add_parser(
            'manage',
            help='Invoke remote Django manage.py commands.'
        )
        rest_help = ("Command in the form of <env> <command>. <env> is not "
                     "required if --all is specified")
        manage_parser.add_argument('--all', action='store_true', help=all_help)
        manage_parser.add_argument('command_rest', nargs='+', help=rest_help)
        manage_parser.add_argument(
            '--no-color', action='store_true',
            help=("Don't color the output")
        )
        # This is explicitly added here because this is the only subcommand that doesn't inherit from env_parser
        # https://github.com/Miserlou/Zappa/issues/1002
        manage_parser.add_argument(
            '-s', '--settings_file', help='The path to a Zappa settings file.'
        )

        ##
        # Rollback
        ##
        def positive_int(s):
            """ Ensure an arg is positive """
            i = int(s)
            if i < 0:
                msg = "This argument must be positive (got {})".format(s)
                raise argparse.ArgumentTypeError(msg)
            return i

        rollback_parser = subparsers.add_parser(
            'rollback', parents=[env_parser],
            help='Rollback deployed code to a previous version.'
        )
        rollback_parser.add_argument(
            '-n', '--num-rollback', type=positive_int, default=1,
            help='The number of versions to rollback.'
        )

        ##
        # Scheduling
        ##
        subparsers.add_parser(
            'schedule', parents=[env_parser],
            help='Schedule functions to occur at regular intervals.'
        )

        ##
        # Status
        ##
        status_parser = subparsers.add_parser(
            'status', parents=[env_parser],
            help='Show deployment status and event schedules.'
        )

        ##
        # Log Tailing
        ##
        tail_parser = subparsers.add_parser(
            'tail', parents=[env_parser], help='Tail deployment logs.'
        )
        tail_parser.add_argument(
            '--no-color', action='store_true',
            help="Don't color log tail output."
        )
        tail_parser.add_argument(
            '--http', action='store_true',
            help='Only show HTTP requests in tail output.'
        )
        tail_parser.add_argument(
            '--non-http', action='store_true',
            help='Only show non-HTTP requests in tail output.'
        )
        tail_parser.add_argument(
            '--since', type=str, default="100000s",
            help="Only show lines since a certain timeframe."
        )
        tail_parser.add_argument(
            '--filter', type=str, default="",
            help="Apply a filter pattern to the logs."
        )
        tail_parser.add_argument(
            '--force-color', action='store_true',
            help='Force coloring log tail output even if coloring support is not auto-detected. (example: piping)'
        )
        tail_parser.add_argument(
            '--disable-keep-open', action='store_true',
            help="Exit after printing the last available log, rather than keeping the log open."
        )

        ##
        # Undeploy
        ##
        undeploy_parser = subparsers.add_parser(
            'undeploy', parents=[env_parser], help='Undeploy application.'
        )
        undeploy_parser.add_argument(
            '--remove-logs', action='store_true',
            help=('Removes log groups of api gateway and lambda task'
                  ' during the undeployment.'),
        )
        undeploy_parser.add_argument(
            '-y', '--yes', action='store_true', help='Auto confirm yes.'
        )

        ##
        # Unschedule
        ##
        subparsers.add_parser('unschedule', parents=[env_parser],
                              help='Unschedule functions.')

        ##
        # Updating
        ##
        update_parser = subparsers.add_parser(
            'update', parents=[env_parser], help='Update deployed application.'
        )
        update_parser.add_argument(
            '-z', '--zip', help='Update Lambda with specific local or S3 hosted zip package'
        )
        update_parser.add_argument(
            '-n', '--no-upload', help="Update configuration where appropriate, but don't upload new code"
        )

        ##
        # Debug
        ##
        subparsers.add_parser(
            'shell', parents=[env_parser], help='A debug shell with a loaded Zappa object.'
        )

        argcomplete.autocomplete(parser)
        args = parser.parse_args(argv)
        self.vargs = vars(args)

        if args.color == 'never':
            disable_click_colors()
        elif args.color == 'always':
            #TODO: Support aggressive coloring like "--force-color" on all commands
            pass
        elif args.color == 'auto':
            pass

        # Parse the input
        # NOTE(rmoe): Special case for manage command
        # The manage command can't have both stage_env and command_rest
        # arguments. Since they are both positional arguments argparse can't
        # differentiate the two. This causes problems when used with --all.
        # (e.g. "manage --all showmigrations admin" argparse thinks --all has
        # been specified AND that stage_env='showmigrations')
        # By having command_rest collect everything but --all we can split it
        # apart here instead of relying on argparse.
        if not args.command:
            parser.print_help()
            return

        if args.command == 'manage' and not self.vargs.get('all'):
            self.stage_env = self.vargs['command_rest'].pop(0)
        else:
            self.stage_env = self.vargs.get('stage_env')

        if args.command == 'package':
            self.load_credentials = False

        self.command = args.command

        self.disable_progress = self.vargs.get('disable_progress')
        if self.vargs.get('quiet'):
            self.silence()

        # We don't have any settings yet, so make those first!
        # (Settings-based interactions will fail
        # before a project has been initialized.)
        if self.command == 'init':
            self.init()
            return

        # Make sure there isn't a new version available
        if not self.vargs.get('json'):
            self.check_for_update()

        # Load and Validate Settings File
        self.load_settings_file(self.vargs.get('settings_file'))

        # Should we execute this for all stages, or just one?
        all_stages = self.vargs.get('all')
        stages = []

        if all_stages: # All stages!
            stages = self.zappa_settings.keys()
        else: # Just one env.
            if not self.stage_env:
                # If there's only one stage defined in the settings,
                # use that as the default.
                if len(self.zappa_settings.keys()) == 1:
                    stages.append(list(self.zappa_settings.keys())[0])
                else:
                    parser.error("Please supply a stage to interact with.")
            else:
                stages.append(self.stage_env)

        for stage in stages:
            try:
                self.dispatch_command(self.command, stage)
            except ClickException as e:
                # Discussion on exit codes: https://github.com/Miserlou/Zappa/issues/407
                e.show()
                sys.exit(e.exit_code)
503328
def popen(*args, **kwargs):
    
    process = subprocess.Popen(*args, **kwargs)
    try:
        yield process.pid
    finally:
        os.kill(process.pid, signal.SIGTERM)
        os.waitpid(process.pid, 0)
576593
def runCommand(cmd, timeout=None, window=None):
    
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ''
    for line in p.stdout:
        line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
        output += line
        print(line)
        window.Refresh() if window else None        # yes, a 1-line if, so shoot me

    retval = p.wait(timeout)
    return (retval, output)
286250
def machined_cli(args, silence = true)
      capture(:stdout) {
        Machined::CLI.start args.split(' ')
      }
    end