Python3命令行和argparse问题

时间:2018-11-24 22:28:31

标签: python python-3.x

请在下面找到我编写的代码(基于作业)和返回的错误消息。我是python的新手,所以如果这很明显,我会提前道歉。

   def get_input_args():

    """
    Retrieves and parses the 3 command line arguments provided by the user when
    they run the program from a terminal window. This function uses Python's
    argparse module to created and defined these 3 command line arguments. If
    the user fails to provide some or all of the 3 arguments, then the default
    values are used for the missing arguments.
    Command Line Arguments:
    1. Image Folder as --dir with default value 'pet_images'
    2. CNN Model Architecture as --arch with default value 'vgg'
    3. Text File with Dog Names as --dogfile with default value 'dognames.txt'
    This function returns these arguments as an ArgumentParser object.
    Parameters:
    None - simply using argparse module to create & store command line arguments
    Returns:
    parse_args() -data structure that stores the command line arguments object
    """

    parser = argparse.ArgumentParser()

    parser.add_argument('--dir', type = str, default =    'pet_images/', help = 'path to the folder of pet images')

    parser.add_argument('--arch', type = str, default = 'vgg', help = 'CNN model Architecture VGG')

    parser.add_argument('--dogfile', type = str, default = 'dognames.txt', help = 'Text File with Dog Names')

# Replace None with parser.parse_args() parsed argument collection that
# you created with this function**

    args = parser.parse_args('--dir', '--arch', '--dogfile')



root@791d23aa2615:/home/workspace# python check_images.py
Traceback (most recent call last):
File "check_images.py", line 131, in <module>
main()
File "check_images.py", line 51, in main
in_arg = get_input_args()
File "/home/workspace/get_input_args.py", line 49, in get_input_args
args = parser.parse_args('--dir', '--arch', '--dogfile')
TypeError: parse_args() takes from 1 to 3 positional arguments but 4 were given

谢谢

在查尔斯回答后,我使用了

args = parser.parse_args()

但是我无法获得默认值

* Doesn't Check the Command Line Arguments because 'get_input_args' hasn't been defined.
* Doesn't Check the Results Dictionary because 'get_pet_labels' hasn't been defined.
* Doesn't Check the Results Dictionary because 'classify_images' hasn't been defined.
* Doesn't Check the Results Dictionary because 'adjust_results4_isadog' hasn't been defined.
* Doesn't Check the Results Dictionary because 'calculates_results_stats' hasn't been defined.

** Total Elapsed Runtime: 0:0:10

2 个答案:

答案 0 :(得分:1)

parse_args在您的回溯中被指示为问题,并且您调用该方法的方式与他们在文档中对它的描述相反。 parse_args()默认从命令行获取args,因此尝试仅将其命名为args = parser.parse_args()

否则,如果您想手动进行操作,则可以执行以下操作:parser.parse_args(['--foo', 'FOO'])

文档:https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_args

答案 1 :(得分:0)

谢谢大家的帮助

我找到了产生默认命令行的答案

return parser.parse_args()

在查尔斯的提示和更多帮助下,我终于找到了它