コード例 #1
0
def _DisplayError(component_trace):
    """Prints the Fire trace and the error to stdout."""
    output = []
    for help_flag in ('-h', '--help'):
        if help_flag in component_trace.elements[-1].args:
            command = '{cmd} -- --help'.format(
                cmd=component_trace.GetCommand())
            message = 'INFO: Showing help with the command {cmd}.\n'.format(
                cmd=pipes.quote(command))
            output.append(message)
    output.append(
        formatting.Error('ERROR: ') +
        component_trace.elements[-1].ErrorAsStr())
    result = component_trace.GetResult()
    help_string = helptext.HelpString(result, component_trace,
                                      component_trace.verbose)
    output.append(help_string)
    Display(output)
コード例 #2
0
def _PrintResult(component_trace, verbose=False):
    """Prints the result of the Fire call to stdout in a human readable way."""
    # TODO(dbieber): Design human readable deserializable serialization method
    # and move serialization to its own module.
    result = component_trace.GetResult()

    if isinstance(result, (list, set, types.GeneratorType)):
        for i in result:
            print(_OneLineResult(i))
    elif inspect.isgeneratorfunction(result):
        raise NotImplementedError
    elif isinstance(result, dict):
        print(_DictAsString(result, verbose))
    elif isinstance(result, tuple):
        print(_OneLineResult(result))
    elif isinstance(result, value_types.VALUE_TYPES):
        print(result)
    elif result is not None:
        print(helptext.HelpString(result, component_trace, verbose))
コード例 #3
0
def Fire(component=None, command=None, name=None):
    """This function, Fire, is the main entrypoint for Python Fire.

  Executes a command either from the `command` argument or from sys.argv by
  recursively traversing the target object `component`'s members consuming
  arguments, evaluating functions, and instantiating classes as it goes.

  When building a CLI with Fire, your main method should call this function.

  Args:
    component: The initial target component.
    command: Optional. If supplied, this is the command executed. If not
        supplied, then the command is taken from sys.argv instead. This can be
        a string or a list of strings; a list of strings is preferred.
    name: Optional. The name of the command as entered at the command line.
        Used in interactive mode and for generating the completion script.
  Returns:
    The result of executing the Fire command. Execution begins with the initial
    target component. The component is updated by using the command arguments
    to either access a member of the current component, call the current
    component (if it's a function), or instantiate the current component (if
    it's a class). When all arguments are consumed and there's no function left
    to call or class left to instantiate, the resulting current component is
    the final result.
  Raises:
    ValueError: If the command argument is supplied, but not a string or a
        sequence of arguments.
    FireExit: When Fire encounters a FireError, Fire will raise a FireExit with
        code 2. When used with the help or trace flags, Fire will raise a
        FireExit with code 0 if successful.
  """
    name = name or os.path.basename(sys.argv[0])

    # Get args as a list.
    if isinstance(command, six.string_types):
        args = shlex.split(command)
    elif isinstance(command, (list, tuple)):
        args = command
    elif command is None:
        # Use the command line args by default if no command is specified.
        args = sys.argv[1:]
    else:
        raise ValueError(
            'The command argument must be a string or a sequence of '
            'arguments.')

    args, flag_args = parser.SeparateFlagArgs(args)

    argparser = parser.CreateParser()
    parsed_flag_args, unused_args = argparser.parse_known_args(flag_args)

    context = {}
    if parsed_flag_args.interactive or component is None:
        # Determine the calling context.
        caller = inspect.stack()[1]
        caller_frame = caller[0]
        caller_globals = caller_frame.f_globals
        caller_locals = caller_frame.f_locals
        context.update(caller_globals)
        context.update(caller_locals)

    component_trace = _Fire(component, args, parsed_flag_args, context, name)

    if component_trace.HasError():
        _DisplayError(component_trace)
        raise FireExit(2, component_trace)
    if component_trace.show_trace and component_trace.show_help:
        output = ['Fire trace:\n{trace}\n'.format(trace=component_trace)]
        result = component_trace.GetResult()
        help_string = helptext.HelpString(result, component_trace,
                                          component_trace.verbose)
        output.append(help_string)
        Display(output)
        raise FireExit(0, component_trace)
    if component_trace.show_trace:
        output = ['Fire trace:\n{trace}'.format(trace=component_trace)]
        Display(output)
        raise FireExit(0, component_trace)
    if component_trace.show_help:
        result = component_trace.GetResult()
        help_string = helptext.HelpString(result, component_trace,
                                          component_trace.verbose)
        output = [help_string]
        Display(output)
        raise FireExit(0, component_trace)

    # The command succeeded normally; print the result.
    _PrintResult(component_trace, verbose=component_trace.verbose)
    result = component_trace.GetResult()
    return result