我几乎完成了我的 argparse 任务,已经连续 8 个小时了,将提供我目前的代码以及运行时应该做什么

I'm almost done with my argparse assignment, have been at this for 8 hours straight, will provide my code so far and what it should do when runs

Here are the instruction for how I'm supposed to build my program:

使用 argparse 实现程序的 CLI 部分,使其工作如下所示。它是本课程中为数不多的实际打印输出的程序之一。

当您使用 -h 帮助标志时,程序的输出应该看起来完全像这样。提示:您可以使用 argparse 免费获得 -h 帮助标志。您不必自己实现 -h 标志。

$ python HW3_cli.py -h 用法:HW3_cli.py[-h][-p][-c][-l]文本[文本...]

位置参数: texts 要操作的输入字符串

可选参数: -h, --help 显示此帮助信息并退出 -p, --print 只打印输入的字符串 -c, --combine 打印组合成连续字符串的输入字符串

-l, --len 打印输入字符串的长度

打印、合并,然后 len。如果没有给出标志,什么也不做。

看到最后的描述行告诉它做什么了吗?它是用 epilog 创建的。

如果根本没有给出任何参数,它应该给出一个错误,指出需要文本参数。提示:如果您对文本参数进行正确编程,您就不会遇到此错误。

$pythonHW3_cli.py 用法:HW3_cli.py[-h][-p][-c][-l]文本[文本...]

HW3_cli.py:错误:需要以下参数:texts

三个标志的行为解释如下。如果至少给出了一个输入字符串,但没有给出标志,则程序应该什么都不做。由于讲座示例中没有使用标志,因此您需要查看 argparse 文档(查看此处的教程)以查找如何实现标志参数。它们在文档中被称为“短选项”。查找实施 -v“详细”选项的示例。

参数

标志参数控制程序的行为。这些标志可以在命令行上以任何顺序或组合给出,但是,这些是实现规则:它们应该按照下面显示的顺序实现 - 换句话说,先执行打印标志(如果给定),然后组合标志(如果给定),然后是 len 标志(如果给定)。请在使用帮助的输出中使所有帮助字符串与上面显示的完全相同,如上所示。请随意从本文档中 copy/paste。

-p 或 --print 标志将打印出每个字符串之间带有空格的输入字符串。我们知道如何使用 str 方法之一从字符串列表中创建一个字符串。

-c 或 --combine 标志将打印所有连接在一起的输入字符串。同样,我们知道如何使用字符串方法来做到这一点。

-l 或 --len 标志打印出每个输入字符串的长度。不,您不需要使用 len_safe,因为它们始终是字符串。这有点更具挑战性,但你可以弄清楚! -l 或 --len 的实施选项包括生成器表达式、打印函数的特殊参数等。

下面是我的代码运行时的样子:

$ python HW3_cli.py -c 连接这些字符串 TheseStringsGetConcatenated $ python HW3_cli.py -c -p 打印并连接这些字符串 这些字符串被打印和连接 这些字符串得到打印和连接 $ python HW3_cli.py -l -c -p 打印并连接这些字符串 这些字符串被打印和连接 这些字符串得到打印和连接 5 7 3 7 3 12 $ python HW3_cli.py -c -l --print 打印并连接这些字符串 这些字符串被打印和连接 这些字符串得到打印和连接 5 7 3 7 3 12 $ python HW3_cli.py --len --combine --print 打印并连接这些字符串 这些字符串被打印和连接 这些字符串得到打印和连接 5 7 3 7 3 12 $ python HW3_cli.py --len --combine a b c d e f g abcdefg 1 1 1 1 1 1 1 $ python HW3_cli.py 测试 $ python HW3_cli.py -l 测试 7$ python HW3_cli.py -p 测试 测试 $ python HW3_cli.py -c 测试 测试

最后,这是我的代码,然后我会分享我得到的错误:

import argparse
        
if __name__ == "__main__":
    # Set up argparse parser and arguments here
    parser = argparse.ArgumentParser(epilog="Does print, combine, then len. If no flags given, does nothing.")
    # Add the arguments here
    parser.add_argument('texts', help='Input strings to operate on')
    parser.add_argument('-p', '--print', action='store_true', help='Just print the input strings')
    parser.add_argument('-c', '--combine', action='store_true', help='Print input strings combined in a continuous string')
    parser.add_argument('-l', '--len', action='store_true', help='Print the lengths of the input strings')
    args = parser.parse_args()
        
    if args.print:
        words = split(str(args.texts))
        print(" ".join(words))
    if args.combine:
        words2 = split(str(args.texts))
        print("".join(words2))
    if args.len:
        for text in split(str(args.texts)):
            print(len(text))

Lastly, the error I get is: $ python HW3_cli.py -c These Strings Get Concatenated usage: HW3_cli.py [-h] [-p] [-c] [-l] texts HW3_cli.py: error: unrecognized arguments: Strings Get Concatenated

如评论中所述,如果您想为 texts 传递多词输入,则需要将它们用引号括起来,例如 ./script "a b c" -p.

但是,这里有一种方法,您不需要将其用引号引起来。这为位置参数 texts 指定了 nargs='*',它是一个贪婪的量词,匹配您传入脚本的所有参数。解析后的结果将作为单词列表传入,因此我们也不需要拆分输入字符串。

import argparse

if __name__ == "__main__":
    # Set up argparse parser and arguments here
    parser = argparse.ArgumentParser(epilog="Does print, combine, then len. If no flags given, does nothing.")
    # Add the arguments here
    parser.add_argument('texts', help='Input strings to operate on',
                        # Add `nargs=*` so we capture as many positional arguments as possible.
                        # The parsed result will be passed in as a list.
                        nargs='*')
    parser.add_argument('-p', '--print', action='store_true', help='Just print the input strings')
    parser.add_argument('-c', '--combine', action='store_true',
                        help='Print input strings combined in a continuous string')
    parser.add_argument('-l', '--len', action='store_true', help='Print the lengths of the input strings')
    args = parser.parse_args()

    if args.print:
        print(" ".join(args.texts))
    if args.combine:
        print("".join(args.texts))
    if args.len:
        # prints output on a single line, separated by spaces
        print(*map(len, args.texts))
        # alternatively, if you want output on each line:
        # for text in args.texts:
        #     print(len(text))

用法示例:

$ python script.py -lcp These Strings Get Printed And Concatenated
These Strings Get Printed And Concatenated
TheseStringsGetPrintedAndConcatenated
5 7 3 7 3 12