2011-08-13 40 views
1

爲了給我的python腳本提供選項,我想介紹一些參數。我發現在python中更好的方法是使用getopt,但是一旦我運行我的腳本,它就不會執行任何操作。請幫幫我!!!。這是我的代碼:無法使用getopt處理參數

def main(argv): 
    try: 
      opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output=']) 
    except getopt.GetoptError: 
      usage() 
      sys.exit(2) 
      file = None 
      outfile = None 
    for opt, arg in opts: 
      if opt in ('-h', '--help'): 
        usage() 
        sys.exit(2) 
      elif opt in ('-i', '--input'): 
        file = arg 
      elif opt in ('-o', '--output'): 
        outfile = arg 
      elif opt == '-t': 
        maininfo(file,outfile) 
      else: 
        usage() 
        sys.exit(2) 

if __name__ =='__main__': 
    main(sys.argv[1:]) 
+3

你能告訴我,在你問之前它不怎麼起作用? msg的錯誤是什麼? –

+0

一旦它修正了'try:'行的縮進,我發現這個工作正如我所料。 ['file'](http://docs.python.org/library/stdtypes.html)是Python中的一個內置類,因此您應該調用其他變量。 – Johnsyweb

+0

@Johnsyweb謝謝,我更改了infile文件,但它不起作用。並且沒有錯誤味精。:(: – Alejandro

回答

5

我建議增加更多的日誌記錄。這不僅會幫助你現在,它會幫助誰將來使用你的腳本。

def main(argv): 
    filename = None 
    outfile = None 
    call_maininfo = False 
    try: 
     opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output=']) 
     if not opts: 
      print 'No options supplied' 
      usage() 
    except getopt.GetoptError, e: 
     print e 
     usage() 
     sys.exit(2) 
    for opt, arg in opts: 
     if opt in ('-h', '--help'): 
      usage() 
      sys.exit(2) 
     elif opt in ('-i', '--input'): 
      filename = arg 
     elif opt in ('-o', '--output'): 
      outfile = arg 
     elif opt == '-t': 
      call_maininfo = True 
     else: 
      usage() 
      sys.exit(2) 

    print 'Processed options [{0}] and found filename [{1}] and outfile [{2}]'.format(
      ', '.join(argv), 
      filename, 
      outfile, 
      ) 

    if call_maininfo: 
     print 'Calling maininfo()' 
     maininfo(filename, outfile) 

我也感動調用maininfo()圈外的,你可以在文件名前提供-t

+0

謝謝@Johnsyweb這是真棒!!!! :) – Alejandro

+0

@alejandro:高興地幫助。 – Johnsyweb

3

您可以使用optparseargparse(舊版本,將蟒蛇2.7後不建議使用)(新版本),這是標準的Python模塊解析參數。

希望它可以幫助這個第一

+2

我想知道爲什麼getopt沒有被刪除但... – JBernardo

+0

這可能是問題?getopt已過時?? – Alejandro