2011-09-26 53 views
5

我在Python中有一個使用函數的問題。這是我的主要功能的一部分:使用函數不能與getopt一起使用

def main(argv): 
    try: 
      opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['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) 
if __name__ =='__main__': 
    main(sys.argv[1:]) 

和我定義的使用功能以及

def usage(): 
    print "\nThis is the usage function\n" 
    print 'Usage: '+sys.argv[0]+' -i <file1> [option]' 

但是當我運行我的代碼爲./code.py./code.py -h(它是可執行的),我得到了什麼,但Python的幫助。

+0

你是什麼意思的「除python幫助之外的任何東西」?每種情況下的輸出究竟是什麼?你的代碼看起來是正確的。 – agf

+0

'用法:python [選項] ... [-c cmd | -m mod |文件| - ] [arg] ...' – Alejandro

+0

您將需要向我們展示更多代碼。我沒有看到什麼觸發了你粘貼的Python使用線。 – agf

回答

5

以下爲我工作。用「python code.py」運行它。

import getopt, sys 

def usage(): 
    print "\nThis is the usage function\n" 
    print 'Usage: '+sys.argv[0]+' -i <file1> [option]' 

def main(argv): 
    try: 
    opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['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) 

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

「我沒有收到錯誤」不是對「爲什麼我收到錯誤」的回答。 – agf

+0

@agf是的,的確如此。這是他的真正目標是獲得工作代碼。如果他只想瞭解爲什麼他的代碼不起作用,我想這不是有幫助的。 – BenH

+0

感謝您的幫助,如果在('-h','--help')中選擇刪除'-':'似乎對我有效......感謝 – Alejandro

相關問題