2014-11-08 27 views
1

我非常喜歡python和optparse模塊。我已經想出瞭如何使用optparse在python腳本中添加選項,但無法將選項與python中的變量名稱鏈接起來。如何在python中集成optparse選項和變量名

import sys 
from optparse import OptionParser 

def main(): 
    parser = OptionParser() 
    parser.add_option("-f", "--file", dest="in_filename", 
         help="Input fasta file", metavar="FILE") 
    parser.add_option("-o", "--out", dest="out_filename", 
         help="Output fasta file", metavar="FILE") 
    parser.add_option("-i", "--id", dest="id", 
         help="Id name to change", metavar="ID") 
    (options,args) = parser.parse_args() 

    with open(f, 'r') as fh_in: 
     with open(o, 'w') as fh_out: 
      id = i 
      result = {} 
      count = 1 
      for line in fh_in: 
       line = line.strip() 
       if line.startswith(">"): 
        line = line[1:] 
        result[line] = id + str(count) 
        count = count + 1 
        header = ">" + str(result[line]) 
        fh_out.write(header) 
        fh_out.write("\n") 
       else: 
        fh_out.write(line) 
        fh_out.write("\n") 

main() 

當我運行此我得到這個下面回溯和錯誤:

python header_change.py -f consensus_seq.txt -o consensus_seq_out.fa -i "my_test" 
Traceback (most recent call last): 
    File "/Users/upendrakumardevisetty/Documents/git_repos/scripts/header_change.py", line 36, in <module> 
    main() 
    File "/Users/upendrakumardevisetty/Documents/git_repos/scripts/header_change.py", line 18, in main 
    with open(f, 'r') as fh_in: 
NameError: global name 'f' is not defined 

有人可以點我什麼我做錯了。

+0

首先,請打印整個回溯,而不僅僅是錯誤字符串。在這種情況下,我們可以猜測它發生的位置,但最好不要讓人猜測。 – abarnert 2014-11-08 02:39:31

+0

增加了追蹤 – upendra 2014-11-08 02:44:28

+0

作爲一個附註,是否有你使用'optparse'的理由?作爲[文檔](https://docs.python.org/2/library/optparse.html)解釋,它已在2.7/3.2中棄用。除非你需要你的程序運行在2.6或3.1版本,否則最好使用'argparse' - 尤其是如果你只是在學習;沒有理由去學習已經過時的東西。 – abarnert 2014-11-08 02:44:53

回答

4

這裏有兩個問題。


首先,the optparse tutorial顯示,optparse不創建全局變量,它會在options命名空間,它返回屬性:

parse_args() returns two values:

  • options , an object containing values for all of your options—e.g. if --file takes a single string argument, then options.file will be the filename supplied by the user, or None if the user did not supply that option
  • args , the list of positional arguments leftover after parsing options

所以,如果用戶鍵入-f,你不會有f,你將有options.f


其次,f不是正確的名字。你明確指定一個不同的目的地,而不是默認的:

parser.add_option("-f", "--file", dest="in_filename", 
        help="Input fasta file", metavar="FILE") 

所以它會做你的要求和文件存儲在in_filename


對於其他選項同樣如此。所以,你的代碼應該像這樣開始:

with open(options.in_filename, 'r') as fh_in: 
    with open(options.out_filename, 'w') as fh_out: 
+0

我明白現在它是如何工作的。謝謝你的幫助 – upendra 2014-11-08 03:16:50

相關問題