2011-10-07 45 views
0

以前我問過一個問題here。該問題已解決,但在開發腳本時出現錯誤。python:AttributeError,'模塊'對象沒有屬性'東西'

目前,一種選擇是從命令行得到這樣的:

... -b b1 

即碼處理:

import Mybench, optparse 
parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.") 
if options.benchmark == 'b1': 
    process = Mybench.b1 
elif options.benchmark == 'b2': 
    process = Mybench.b2 
... 
else: 
    print "no such benchmark!" 

現在我已經改變了,這樣不止一個選項傳遞給「 - b」。

... -b b1,b2 

這個代碼是:

process = [] 
benchmarks = options.benchmark.split(',') 
for bench_name in benchmarks: 
    print bench_name 
    process.append(Mybench.bench_name) 

如果你注意到,在第一碼進程得到這樣的值:

process = Mybench.b1 

現在我寫這篇文章:

process.append(Mybench.bench_name) 

我希望這個命令lin E:在

... -b b1,b2 

結果:

process[0] = Mybench.b1 
process[1] = Mybench.b2 

但是我得到這個錯誤:

process.append(Mybench.bench_name) 
AttributeError: 'module' object has no attribute 'bench_name' 

有什麼解決辦法嗎?

回答

4

bench_name是一個字符串,而不是一個標識符,所以你需要使用getattr()

process.append(getattr(Mybench, bench_name)) 
2

對於我來說,是不同的:
- process.b1
- process.bench_name =>過程。 「b1」

getattr()可能是你遺囑的關鍵。

相關問題