我非常喜歡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
有人可以點我什麼我做錯了。
首先,請打印整個回溯,而不僅僅是錯誤字符串。在這種情況下,我們可以猜測它發生的位置,但最好不要讓人猜測。 – abarnert 2014-11-08 02:39:31
增加了追蹤 – upendra 2014-11-08 02:44:28
作爲一個附註,是否有你使用'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