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

时间:2010-03-19 10:06:00

标签: 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: ")

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

  

以最好的方式指导我   它..

4 个答案:

答案 0 :(得分:16)

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

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

答案 1 :(得分:1)

如果optparse不能满足您的所有需求,

argparse是另一种选择

optparse vs argparse

答案 2 :(得分:1)

虽然正确的做法是使用optparse,但是对代码的一些评论 - 如所呈现的那样 - 是有序的。

四个条件标志(ask_username,ask_password,ask_message,ask_number)没用。

考虑这四个项目中的任何一个的后置条件(它们都是相同的)

(in_args AND variable_set) OR (not in_args AND prompt AND variable_set)

你真的在做这样的事情。

username= None 

# Pre Condition: username is not set to a useful value

# ... use `optparse` to parse options ... 
username = options.username 

# Post Condition: username may be None if no option provided
# or username may be set if an option was provided.

if username is None: # it's not set to a useful value
    # ... prompt to get a value for username ... 

assert username is not None

如果您的默认值更有用,则不需要任何标记。

答案 3 :(得分:1)

到目前为止, optparse 符合我的所有需求。