2016-01-20 40 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="])