Python argparse 模块,parse_args() 实例源码

我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用argparse.parse_args()

项目:nojs    作者:chrisdickinson    | 项目源码 | 文件源码
def ParseArgs(args):
  """Parses command line options.

  Returns:
    An Namespace from argparse.parse_args()
  """
  parser = argparse.ArgumentParser(prog='generate_resource_rewriter')

  parser.add_argument('--package-name',
                      required=True,
                      help='The package name of ResourceRewriter.')
  parser.add_argument('--dep-packages',
                      required=True,
                      help='A list of packages whose resource id will be'
                           'overwritten in ResourceRewriter.')
  parser.add_argument('--output-dir',
                      help='A output directory of generated'
                           ' ResourceRewriter.java')
  parser.add_argument('--srcjar',
                      help='The path of generated srcjar which has'
                           ' ResourceRewriter.java')

  return parser.parse_args(args)
项目:chromium-build    作者:discordapp    | 项目源码 | 文件源码
def ParseArgs(args):
  """Parses command line options.

  Returns:
    An Namespace from argparse.parse_args()
  """
  parser = argparse.ArgumentParser(prog='generate_resource_rewriter')

  parser.add_argument('--package-name',
                      required=True,
                      help='The package name of ResourceRewriter.')
  parser.add_argument('--dep-packages',
                      required=True,
                      help='A list of packages whose resource id will be'
                           'overwritten in ResourceRewriter.')
  parser.add_argument('--output-dir',
                      help='A output directory of generated'
                           ' ResourceRewriter.java')
  parser.add_argument('--srcjar',
                      help='The path of generated srcjar which has'
                           ' ResourceRewriter.java')

  return parser.parse_args(args)
项目:gn_build    作者:realcome    | 项目源码 | 文件源码
def ParseArgs(args):
  """Parses command line options.

  Returns:
    An Namespace from argparse.parse_args()
  """
  parser = argparse.ArgumentParser(prog='generate_resource_rewriter')

  parser.add_argument('--package-name',
                      required=True,
                      help='The package name of ResourceRewriter.')
  parser.add_argument('--dep-packages',
                      required=True,
                      help='A list of packages whose resource id will be'
                           'overwritten in ResourceRewriter.')
  parser.add_argument('--output-dir',
                      help='A output directory of generated'
                           ' ResourceRewriter.java')
  parser.add_argument('--srcjar',
                      help='The path of generated srcjar which has'
                           ' ResourceRewriter.java')

  return parser.parse_args(args)
项目:transmission_scripts    作者:leighmacdonald    | 项目源码 | 文件源码
def make_client(args=None):
    """ Create a new transmission RPC client

    If you want to parse more than the standard CLI arguments, like when creating a new customized
    script, you can append your options to the argument parser.

    :param args: Optional CLI args passed in.
    :return:
    """
    if args is None:
        args = parse_args()
    if args.generate:
        generate_config(args.force)
    load_config()
    return TSClient(
        args.host or CONFIG['CLIENT']['host'],
        port=args.port or CONFIG['CLIENT']['port'],
        user=args.user or CONFIG['CLIENT']['user'],
        password=args.password or CONFIG['CLIENT']['password']
    )
项目:nodenative    作者:nodenative    | 项目源码 | 文件源码
def ParseArgs(args):
  """Parses command line options.

  Returns:
    An Namespace from argparse.parse_args()
  """
  parser = argparse.ArgumentParser(prog='generate_resource_rewriter')

  parser.add_argument('--package-name',
                      required=True,
                      help='The package name of ResourceRewriter.')
  parser.add_argument('--dep-packages',
                      required=True,
                      help='A list of packages whose resource id will be'
                           'overwritten in ResourceRewriter.')
  parser.add_argument('--output-dir',
                      help='A output directory of generated'
                           ' ResourceRewriter.java')
  parser.add_argument('--srcjar',
                      help='The path of generated srcjar which has'
                           ' ResourceRewriter.java')

  return parser.parse_args(args)
项目:transmission_scripts    作者:leighmacdonald    | 项目源码 | 文件源码
def make_arg_parser():
    """ Create a new argparse instance that can optionally be extended to include custom
    options before passing the options into the client as demonstrated below.

    >>> def parse_args():
    >>>     parser = argparse.ArgumentParser(
    >>>         description='Clean out old torrents from the transmission client via RPC',
    >>>         parents=[make_arg_parser()]
    >>>     )
    >>>     parser.add_argument("--example", "-e", dest="example", help="Example command")
    >>>     return parser.parse_args()
    >>> args = parse_args()


    :return: New argparse instance
    :rtype: argparse.ArgumentParser
    """
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--host', '-H', default=None, type=str, help="Transmission RPC Host")
    parser.add_argument('--port', '-p', type=int, default=0, help="Transmission RPC Port")
    parser.add_argument('--user', '-u', default=None, help="Optional username", dest="user")
    parser.add_argument('--password', '-P', default=None, help="Optional password", dest='password')
    parser.add_argument('--generate_config', '-g', dest='generate', action='store_true',
                        help="Generate a config file that can be used to override defaults")
    parser.add_argument('--force', '-f', help="Overwrite existing files",
                        dest='force', action='store_true')
    return parser
项目:transmission_scripts    作者:leighmacdonald    | 项目源码 | 文件源码
def parse_args():
    """ Trivial shortcut to calling the default argparse.parse_args()

    :return:
    """
    return make_arg_parser().parse_args()
项目:spartacus    作者:CommunicationsSecurityEstablishment    | 项目源码 | 文件源码
def validatePaths(argsWithPaths):
    """
    This function will simply validate that the input path exists and that the output path
    is free for the system to use
    :param argsWithPaths: An input parsed object as provided by argparse.parse_args()
    :return: This does not return. Simply raises ValueError in cases where paths are not valid.
    """
    for file in argsWithPaths.input:
        if not os.path.exists(file):
            raise ValueError("ERROR: file {} does not exists.".format(file,))
项目:spartacus    作者:CommunicationsSecurityEstablishment    | 项目源码 | 文件源码
def parseCommandLineArgs():
    """
    As implied by the name, this will parse the command line arguments so we can use them.
    :return: A parsed object as provided by argparse.parse_args()
    """
    parser = argparse.ArgumentParser(prog="Debugger.py",
                                     description="Capua On Chip Debugger Version {}".format(__version__,),
                                     epilog="This tool is provided as part of Spartacus learning environment under {} "
                                            "licence. Feel free to distribute, modify, "
                                            "contribute and learn!".format(__license__,))
    parser.add_argument("-i", "--input",
                        required=True,
                        type=str,
                        help="Define the input file(s) to be used.")

    parser.add_argument("-o", "--output",
                        required=False,
                        nargs=1,
                        type=str,
                        help="This is optional. If present, debugging session will be logged to specified file")

    parser.add_argument("-a", "--address",
                        required=False,
                        nargs=1,
                        type=int,
                        default=None,
                        help="Define the address at which a binary should be loaded.")

    parser.add_argument("-s", "--software",
                        required=False,
                        nargs=1,
                        type=bool,
                        default=False,
                        help="This is required if -s option was used on the linker. That will allow "
                             "binary to be loader at correct address specified inside the binary")

    args = parser.parse_args()

    return args
项目:spartacus    作者:CommunicationsSecurityEstablishment    | 项目源码 | 文件源码
def validatePaths(argsWithPaths):
    """
    This function will simply validate that the input path exists and that the output path
    is free for the system to use
    :param argsWithPaths: An input parsed object as provided by argparse.parse_args()
    :return: This does not return. Simply raises ValueError in cases where paths are not valid.
    """
    gotSymbols = False
    if not os.path.exists(argsWithPaths.input):
        raise ValueError("ERROR: file {} does not exists.".format(argsWithPaths.input,))
    else:
        if os.path.exists(argsWithPaths.input.split(".")[0] + ".sym"):
            gotSymbols = True

    return gotSymbols
项目:spartacus    作者:CommunicationsSecurityEstablishment    | 项目源码 | 文件源码
def parseCommandLineArgs():
    """
    This simply parses the command line so we can get both players file information
    :return: A parsed object as provided by argparse.parse_args()
    """
    parser = argparse.ArgumentParser(prog="Game.py",
                                     description="Capua Assembler Version {}".format(__version__,),
                                     epilog="This tool is provided as part of Spartacus learning environment under {} "
                                            "licence. Feel free to distribute, modify, "
                                            "contribute and learn!".format(__license__,))
    parser.add_argument("-1", "--p1",
                        required=True,
                        nargs=1,
                        type=str,
                        help="Define the player 1 binary file to be loaded")

    parser.add_argument("-2", "--p2",
                        required=True,
                        nargs=1,
                        type=str,
                        help="Define the player 2 binary file to be loaded")

    args = parser.parse_args()
    args.p1 = os.path.abspath(args.p1[0])  # This originally come out as a list
    args.p2 = os.path.abspath(args.p2[0])

    return args
项目:spartacus    作者:CommunicationsSecurityEstablishment    | 项目源码 | 文件源码
def validatePaths(argsWithPaths):
    """
    This function will simply validate that both paths exists
    :param argsWithPaths: An input parsed object as provided by argparse.parse_args()
    :return: This does not return. Simply raises ValueError in cases where paths are not valid.
    """
    if not os.path.exists(argsWithPaths.p1):
        raise ValueError("ERROR: file {} does not exists.".format(argsWithPaths.p1,))
    if not os.path.exists(argsWithPaths.p2):
        raise ValueError("ERROR: file {} does not exists.".format(argsWithPaths.p2,))
项目:ProGENI    作者:KnowEnG    | 项目源码 | 文件源码
def parse_args():
    """
    Parse the arguments.
    Parse the command line arguments/options using the argparse module
    and return the parsed arguments (as an argparse.Namespace object,
    as returned by argparse.parse_args()).
    Returns:
        argparse.Namespace: the parsed arguments
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('input_expression', type=str,
                        help='name of the file containg expression data')
    parser.add_argument('input_response', type=str,
                        help='name of the file containg response data')
    parser.add_argument('input_network', type=str,
                        help='name of the file containg network data')
    parser.add_argument('-s', '--seed', type=int, default=1011,
                        help='seed used for random generator')
    parser.add_argument('-pt', '--prob_restart_trans', type=float, default=0.5,
                        help='restart probability of RWR to network-transform expression')
    parser.add_argument('-t', '--tolerance', type=float, default=1e-8,
                        help='tolerance used to determine convergence of RWR')
    parser.add_argument('-mi', '--max_iteration', type=int, default=100,
                        help='maximum number of iterations used in RWR')
    parser.add_argument('-nb', '--num_bootstrap', type=int, default=1,
                        help='number of bootstrap samplings')
    parser.add_argument('-pb', '--percent_bootstrap', type=int, default=100,
                        help='percent of samples for bootstrap samplinga (between 0-100)')
    parser.add_argument('-de', '--directory_expression', type=str,
                        default='./',
                        help='directory containing expression data')
    parser.add_argument('-dr', '--directory_response', type=str,
                        default='./',
                        help='directory containing response data')
    parser.add_argument('-dn', '--directory_network', type=str,
                        default='./',
                        help='directory containing network data')
    parser.add_argument('-do', '--directory_out', type=str,
                        default='./',
                        help='directory for the results')
    parser.add_argument('-o', '--output', type=str,
                        default='results.csv',
                        help='name of the file containg the results')
    args = parser.parse_args()
    return args


###############################################################################
项目:ProGENI    作者:KnowEnG    | 项目源码 | 文件源码
def parse_args():
    """
    Parse the arguments.
    Parse the command line arguments/options using the argparse module
    and return the parsed arguments (as an argparse.Namespace object,
    as returned by argparse.parse_args()).
    Returns:
        argparse.Namespace: the parsed arguments
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('input_expression', type=str,
                        help='name of the file containg expression data')
    parser.add_argument('input_response', type=str,
                        help='name of the file containg response data')
    parser.add_argument('input_network', type=str,
                        help='name of the file containg network data')
    parser.add_argument('-s', '--seed', type=int, default=1011,
                        help='seed used for random generator')
    parser.add_argument('-nr', '--num_RCG', type=int, default=100,
                        help='number of genes in the response-correlated gene (RCG) set')
    parser.add_argument('-pt', '--prob_restart_trans', type=float, default=0.5,
                        help='restart probability of RWR to network-transform expression')
    parser.add_argument('-pr', '--prob_restart_rank', type=float, default=0.5,
                        help='restart probability for RWR used to rank nodes w.r.t. RCG')
    parser.add_argument('-t', '--tolerance', type=float, default=1e-8,
                        help='tolerance used to determine convergence of RWR')
    parser.add_argument('-mi', '--max_iteration', type=int, default=100,
                        help='maximum number of iterations used in RWR')
    parser.add_argument('-nb', '--num_bootstrap', type=int, default=1,
                        help='number of bootstrap samplings')
    parser.add_argument('-pb', '--percent_bootstrap', type=int, default=100,
                        help='percent of samples for bootstrap samplinga (between 0-100)')
    parser.add_argument('-de', '--directory_expression', type=str,
                        default='./',
                        help='directory containing expression data')
    parser.add_argument('-dr', '--directory_response', type=str,
                        default='./',
                        help='directory containing response data')
    parser.add_argument('-dn', '--directory_network', type=str,
                        default='./',
                        help='directory containing network data')
    parser.add_argument('-do', '--directory_out', type=str,
                        default='./',
                        help='directory for the results')
    parser.add_argument('-o', '--output', type=str,
                        default='results.csv',
                        help='name of the file containg the results')
    args = parser.parse_args()
    return args


###############################################################################
项目:spartacus    作者:CommunicationsSecurityEstablishment    | 项目源码 | 文件源码
def parseCommandLineArgs():
    """
    As implied by the name, this will parse the command line arguments so we can use them.
    :return: A parsed object as provided by argparse.parse_args()
    """
    parser = argparse.ArgumentParser(prog="Linker.py",
                                     description="Capua Static Flat Linker Version {}".format(__version__,),
                                     epilog="This tool is provided as part of Spartacus learning environment under {} "
                                            "licence. Feel free to distribute, modify, "
                                            "contribute and learn!".format(__license__,))
    parser.add_argument("-i", "--input",
                        required=True,
                        nargs="+",  # Using "+" here allows for variable number or parameters associated with this option
                        type=str,
                        help="Define the input file(s) to be used by the linker.")

    parser.add_argument("-o", "--output",
                        required=False,
                        nargs=1,
                        type=str,
                        default=UNDEFINED,
                        help="Define the output file where the linker data will be written. If not specified, this "
                             "will default to the input file name.")

    parser.add_argument("-a", "--address",
                        required=False,
                        nargs=1,
                        type=int,
                        default=DEFAULT_LOAD_ADDRESS,
                        help="Define the address at which a binary should be loaded. Don't mess this up, "
                             "Capua does not currently have virtual addressing mode... This means that you"
                             "HAVE TO MAKE SURE that your binary is loaded in a free memory region otherwise"
                             "you will destroy other programs!")

    parser.add_argument("-s", "--software",
                        required=False,
                        nargs=1,
                        type=bool,
                        default=False,
                        help="This specifies if the load happens by hardware or software. If it happens by"
                             "software, the load address will be but in the first 4 bytes of the final file"
                             "so that software can know where to put the binary in memory. Otherwise, the address"
                             "will not be added and the load will happen at hardware specified address.")

    args = parser.parse_args()
    args.output = args.output[0] if type(args.output) is not str else args.input[0].split(".")[0]  # Using input as default

    return args
项目:spartacus    作者:CommunicationsSecurityEstablishment    | 项目源码 | 文件源码
def parseCommandLineArgs():
    """
    As implied by the name, this will parse the command line arguments so we can use them. Important note,
    after this function is called, no need to use the "extension" attribute since this one is concatenated
    with the "output". This results in cleaner code since those two are always(? most of the time at least)
    used together.
    :return: A parsed object as provided by argparse.parse_args()
    """
    parser = argparse.ArgumentParser(prog="Assembler.py",
                                     description="Capua Assembler Version {}".format(__version__,),
                                     epilog="This tool is provided as part of Spartacus learning environment under {} "
                                            "licence. Feel free to distribute, modify, "
                                            "contribute and learn!".format(__license__,))
    parser.add_argument("-i", "--input",
                        required=True,
                        nargs=1,
                        type=str,
                        help="Define the input file to be used by the assembler.")

    parser.add_argument("-o", "--output",
                        required=False,
                        nargs=1,
                        type=str,
                        default=UNDEFINED,
                        help="Define the output file where the assembled data will be written. If not specified, this "
                             "will default to the input file name, minus the extension, plus the --extension "
                             "provided value.")

    parser.add_argument("-e", "--extension",
                        required=False,
                        nargs=1,
                        type=str,
                        default=DEFAULT_OUTPUT_EXTENSION,
                        help="Default output extension for the output file. This is useful if changing extension value "
                             "while keeping default output file name. Default value for this is {} please note that "
                             "the '.' has to be provided by the user!".format(DEFAULT_OUTPUT_EXTENSION,))

    args = parser.parse_args()
    args.input = args.input[0]  # This originally come out as a list
    args.output = args.output[0] if type(args.output) is not str else args.input.split(".")[0]  # Using input as default
    args.extension = args.extension[0] if type(args.extension) is not str else args.extension
    args.output = args.output + args.extension if args.output.split(".")[-1] != "o" else args.output  # Just so we don't have to keep typing this...

    return args