2016-01-20 68 views
0

如果我使用命令python main.py -h,它会返回“Home”。
如果我使用命令python main.py -c,它也会返回“Home”而不是“a”。python else if undefined error,view other object

问题在哪里?

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import sys 
import getopt 

######################################################################################  
def usage(): 
    print "Home" 
#if __name__ == "__main__": 
try: 
    opts, args = getopt.getopt(sys.argv[1:], "h:c:u", ["help", "connect", "upload="]) 
except getopt.GetoptError: 
    usage() 
    sys.exit(2) 

for opt, arg in opts: 
    if opt in ("-h", "--help"): 
     usage() 
    elif opt in ("-u", "--upload"): 
     file = args 
     if not file: 
      print "Nie wybrano pliku!" 
     else: 
      print "Wybrany plik",file 
    elif opt in ("-c", "--connect"): 
     print "a" 
+0

顺便说一句,Python的文件说:“在'getopt'模块是命令行选项,其API被设计为一个解析器熟悉C'getopt()'函数的用户,不熟悉C'getopt()'函数的用户,或者希望编写更少代码并获得更好帮助和错误消息的用户应考虑使用'argparse'模块代替。” –

+0

另外,你能想到一个更好的标题?现在,它似乎与这个问题没有任何关系...... –

回答

2

你可能收到getopt.GetoptError例外,在这两种情况下,因为你上市“-h”和“-c”选项,如果他们需要的参数,并根据你的描述,你不传递任何。

考虑更改线路:

opts, args = getopt.getopt(sys.argv[1:], "h:c:u", ["help", "connect", "upload="]) 

到:

opts, args = getopt.getopt(sys.argv[1:], "hcu:", ["help", "connect", "upload="])