Tries to fetch the given subcommand, printing a message with the
        appropriate command called from the command line (usually
        "jira.py") if it can't be found.
866
def fetch_command(self, subcommand):
        
        # Get commands outside of try block to prevent swallowing exceptions
        commands = get_commands()
        try:
            app_name = commands[subcommand]
        except KeyError:
            # This might trigger ImproperlyConfigured (masked in get_commands)
            settings.INSTALLED_APPS
            sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
                (subcommand, self.prog_name))
            sys.exit(1)
        if isinstance(app_name, BaseCommand):
            # If the command is already loaded, use it directly.
            klass = app_name
        else:
            klass = load_command_class(app_name, subcommand)
        return klass
1236972
def command(command, options)
      options = {
          'print_command' => false,
          'failure_message' => "required command '#{command}' is not available."
      }.merge(string_keys(options))
      system_exit_on_error("which #{command}", options)
    end
910169
def execute(self):
        
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        no_settings_commands = [
            'help', 'version', '--help', '--version', '-h',
            'compilemessages', 'makemessages',
            'startapp', 'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special cases for 'jira.py --version' and 'jira.py --help' to work.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
5165
def _get_subcommand(name):
    # type: (str) -> config.RcliEntryPoint
    
    _LOGGER.debug('Accessing subcommand "%s".', name)
    if name not in settings.subcommands:
        raise ValueError(
            '"{subcommand}" is not a {command} command. \'{command} help -a\' '
            'lists all available subcommands.'.format(
                command=settings.command, subcommand=name)
        )
    return settings.subcommands[name]
820788
def subcommand(self, name, help):
    
    if self._subcommands is None:
      self._subcommands = self.add_subparsers(help='commands')
    return self._subcommands.add_parser(name, description=help, help=help)
1232916
def _call_cmd_line(self):
        """"""
        try:
            logging.info("Calling Popen with: {}".format(self.args))
            p = Popen(self.args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        except OSError:
            raise(RuntimeError("No such command found in PATH"))

        # Calling this command with newline as stdin as the
        # iCommnads hangs waiting for user input if the password
        # has not been set or has timed out.
        self.stdout, self.stderr = p.communicate("\n".encode())
        self.stdout = self.stdout.decode("utf-8")
        self.stderr = self.stderr.decode("utf-8")
        self.returncode = p.returncode
1103683
def _call(self, command, ignore_errors=None):
        
        if ignore_errors is None:
            ignore_errors = []
        cmd = []
        cmd.extend(self._prefix)
        cmd.extend([self._path, "-iP"])
        cmd.extend(command)
        command = cmd

        logger.debug("Cmd %s" % command)
        null = open('/dev/null', 'w')
        retcode = subprocess.call(command, stdout=null, stderr=null)
        null.close()

        if retcode in ignore_errors:
            logger.debug(
                "<-- Cmd %s returned %d (ignored)" % (command, retcode))
            return

        if retcode:
            logger.error(
                "<-- Cmd %s returned: %d (error)" % (command, retcode))
            raise subprocess.CalledProcessError(retcode, command)

        logger.debug("<-- Returned %d (good)" % retcode)
        return
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
106428
def print_help(self, prog_name, subcommand):
        
        parser = self.create_parser(prog_name, subcommand)
        parser.print_help()
1329598
def shell(command, *args):
	''''''
	if args:
		command = command.format(*args)

	print LOCALE['shell'].format(command)

	try:
		return subprocess.check_output(command, shell=True)
	except subprocess.CalledProcessError, ex:
		return ex
1142590
def _run_cmd_get_output(cmd):
    
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    out, err = process.communicate()
    return out or err
1167724
def _call(self, command, ignore_errors=None):
        
        if ignore_errors is None:
            ignore_errors = []

        command = self._get_command(command)
        logger.debug("Cmd %s" % command)
        null = open('/dev/null', 'w')
        retcode = subprocess.call(command, stdout=null, stderr=null)
        null.close()

        if retcode in ignore_errors:
            logger.debug(
                "<-- Cmd %s returned %d (ignored)" % (command, retcode))
            return

        if retcode:
            logger.error(
                "<-- Cmd %s returned: %d (error)" % (command, retcode))
            raise subprocess.CalledProcessError(retcode, command)

        logger.debug("<-- Returned %d (good)" % retcode)
        return
446781
def call_output(cmd, stdin=None, encoding_errors="replace", **kwargs):
    """"""
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
    stdout, stderr, retcode = [], [], None
    while retcode is None:
        if stdin is not None:
            logger.log_prefix("<0 ", stdin.rstrip())
        raw_out, raw_err = p.communicate(stdin)
        stdin = None

        out = raw_out.decode(get_encoding(sys.stdout), encoding_errors) if raw_out else ""
        if out:
            logger.log_prefix("1> ", out.rstrip())
        stdout.append(out)

        err = raw_err.decode(get_encoding(sys.stderr), encoding_errors) if raw_err else ""
        if err:
            logger.log_prefix("2> ", err.rstrip())
        stderr.append(err)

        retcode = p.poll()
    return stdout, stderr, retcode
483427
def print_help(self, prog_name, subcommand):
        
        parser = self.get_parser(prog_name, subcommand)
        parser.print_help()
1197289
def do_cmd(self, line):
        ''''''
        try:
            args = self.cmd_parser.parse_args(line.split())
        except ValueError as err:
            return error(err)

        # Check if args.service is valid
        if args.service not in SUPPORTED_SERVICES:
            return error('No Service: ' + args.service)

        args.params = ''.join(args.params)
        # params is optional
        if not args.params.strip():
            args.params = '{}'

        # params must be a dictionary format string
        match = re.match(r"^.*?(\{.*\}).*$", args.params)
        if not match:
            return error('Invalid params')

        try:
            args.params = dict(literal_eval(match.group(1)))
        except ValueError as err:
            return error('Invalid params')

        try:
            # Get ONVIF service
            service = self.client.get_service(args.service)
            # Actually execute the command and get the response
            response = getattr(service, args.operation)(args.params)
        except MethodNotFound as err:
            return error('No Operation: %s' % args.operation)
        except Exception as err:
            return error(err)

        if isinstance(response, (Text, bool)):
            return success(response)
        # Try to convert instance to dictionary
        try:
            success(ONVIFService.to_dict(response))
        except ONVIFError:
            error({})
826551
def run(self):
        
        # Print task title
        print_title(self._task_name_title)

        # Get context object
        ctx = self._ctx

        # Get command parts
        cmd_part_s = self._parts

        # Print title
        print_title('Find program')

        # Get program path from command parts
        program_path = cmd_part_s[0]

        # If the program path ends with one of the file extensions below
        if program_path.endswith(('.exe', '.com', '.bat', '.cmd')):
            # Remove the file extension.
            # This is because `Waf`'s `find_binary` function adds each of the
            # file extensions when finding the program.
            program_path = program_path[:-4]

        # Print info
        print_text('Find program: {0}'.format(program_path))

        #
        try:
            # Find program
            found_program_path_s = ctx.find_program(program_path, quiet=True)

        # If program paths are not found
        except ConfigurationError:
            # Get error message
            msg = 'Error (2D7VS): Program is not found: {0}'.format(
                program_path
            )

            # Raise error
            raise ValueError(msg)

        # If program paths are found.

        # If program paths are found.
        #     Use the first program path found.
        # If program paths are not found. (Should not happen.)
        #     Use given program path.
        found_program_path = found_program_path_s[0] \
            if found_program_path_s else program_path

        # Use the program path found as the first command part
        cmd_part_s[0] = found_program_path

        # Print info
        print_text('Use program: {0}'.format(found_program_path))

        # Print end title
        print_title('Find program', is_end=True)

        # Print title
        print_title('PATH')

        # Print environment variable PATH's value, one part per line
        print_text('\n'.join(os.environ.get('PATH', '').split(os.pathsep)))

        # Print end title
        print_title('PATH', is_end=True)

        # Print title
        print_title('PYTHONPATH')

        # Print environment variable PYTHONPATH's value, one part per line
        print_text(
            '\n'.join(os.environ.get('PYTHONPATH', '').split(os.pathsep))
        )

        # Print end title
        print_title('PYTHONPATH', is_end=True)

        # Print title
        print_title('DIR')

        # Print working directory
        print_text(self._cwd)

        # Print end title
        print_title('DIR', is_end=True)

        # Print title
        print_title('CMD')

        # Print the command in multi-line format
        print_text(_format_multi_line_command(cmd_part_s))

        # Print end title
        print_title('CMD', is_end=True)

        # Print title
        print_title('RUN')

        # Run the command in the working directory
        exit_code = self.exec_command(cmd_part_s, cwd=self._cwd)

        # Print the command's exit code
        print_text('Exit code: {0}'.format(exit_code))

        # Print end title
        print_title('RUN', is_end=True)

        # Print task end title
        print_title(self._task_name_title, True)

        # Return the exit code
        return exit_code
1109634
def get_command(self, *path):
        """"""
        path_str = ':'.join(path)

        if path_str in self.commands:
            return self.commands[path_str].load()

        return None