这是处理命令行参数的正确方法吗?

Abh*_*ogi 2 python

ask_username = True
ask_password = True
ask_message = True
ask_number = True

def Usage():
    print '\t-h, --help:  View help'
    print '\t-u, --username: Username'
    print '\t-p, --password: Password'
    print '\t-n, --number: numbber to send the sms'
    print '\t-m, --message: Message to send'
    sys.exit(1)


opts, args = getopt(sys.argv[1:], 'u:p:m:n:h',["username=","password=","message=","number=","help"])

print opts, args
for o,v in opts:
    if o in ("-h", "--help"):
        Usage()
    elif o in ("-u", "--username"):
        username = v
        ask_username = False
    elif o in ("-p", "--password"):
        passwd = v
        ask_password = False
    elif o in ("-m", "--message"):
        message = v
        ask_message = False
    elif o in ("-n", "--number"):
        number = v
        ask_number = False

#Credentials taken here
if ask_username: username = raw_input("Enter USERNAME: ")
if ask_password: passwd = getpass()
if ask_message: message = raw_input("Enter Message: ")
if ask_number: number = raw_input("Enter Mobile number: ")
Run Code Online (Sandbox Code Playgroud)

我不认为是,因为我正在使用4个对象来检查是否提供了命令行参数...

用最好的方式指导我..

And*_*ett 16

您可能会发现optparse模块很有用 - 它允许您指定所需的选项及其类型和帮助文本,然后解析选项并获取所有结果.

它还会为您自动生成帮助输出,因此您只需将选项保留在一个位置即可.

  • +1:没有别的. (2认同)