我需要从命令行验证参数

时间:2019-09-27 19:00:38

标签: python

我需要确保当我从命令行运行此命令并且不输入任何参数时,显示一条消息(请参阅最后的打印语句),但是我得到的却是:

C:\> python submitted.py (no arguments here)
usage: submitted.py [-h] user_string
submitted.py: error: the following arguments are required: user_string

我该如何进行这项工作? 这是代码:

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument('user_string', help='User string')
args = argparser.parse_args()
user_string = 0

# loop to check all conditions
if args.user_string:
    user_string = args.user_string
    # this will put the inputed words into a list
    words_to_sort = user_string.split()
    # Checking the number of inputs by user to meet criteria
    if len(words_to_sort) < 2:
        # alerts user to input more than 1 word
        print("Invalid command line arguments to program. Please, supply two or more strings to sort.")
    else:
        # sorts the list alphabetically
        words_to_sort.sort()
        # looping thru the list to display them
        for word in words_to_sort:
            # displaying the list
            print(word)
else:
    # if criteria not met user gets another message
    if (user_string < 1):
        print("Please input your words to be sorted")

0 个答案:

没有答案