2012-02-06 14 views
0

我有一個問題,我試圖從另一個模塊使用函數,但該函數調用一個調試函數,該函數檢查全局變量是否具有某個特定屬性。當我導入函數時,這個全局變量沒有被設置(否則使用parser.parse_args來設置),因此函數會報告該屬性不存在。爲了澄清:如何在Python中的其他模塊中解決未初始化的全局變量?

文件findfile.py

_args = {} 

def _debug(msg): 
    if _TEST and _args.debug: 
     print msg 

def findfile(filename): 
    ... 
    _debug("found file") 
    ... 

if __name__ == "__main__": 
    ... 
    _args = parser.parse_args() 
    ... 

文件copyafile.py

import findfile 

findfile.findfile("file1") 

這給了我

AttributeError: 'dict' object has no attribute 'debug' 

現在我明白了parser.parse_args()返回一個命名空間(??)和_args.debug是不是真的在尋找dict。但我的問題是:如何在這種情況下正確地分配_args來設置_args.debugFalse

我不能更改findfile.py但我可以更改copyafile.py

這些事情通常如何處理?在腳本中啓用調試標誌的Python方法是什麼?

回答

1

findfile.py是錯誤的,因爲它是書面,但你可以嘗試讓反正它的工作的東西,如設置您的Argumentparser

parser.add_argument('debug', action='store_true') 

,然後用:

import findfile 
findfile._args = parser.parse_args() 

有你_args.debug默認設置爲False

關於你的錯誤:

你得到AttributeError: 'dict' object has no attribute 'debug',怎麼一回事,因爲你試圖訪問一個dict一樣,如果它是一個Namespace

也許一個例子來闡明什麼Namespace是:

>>> d = {'apple': 'red'} 
>>> d['apple'] 
'red' 
>>> from argparse import Namespace 
>>> ns = Namespace(apple='red') 
>>> ns.apple 
'red' 
+0

如果我的理解是否正確,你要我在我的文件中創建一個參數解析器和設置_args變量的其他模塊?我無法更改第一個文件 – sPirc 2012-02-06 10:00:03

+0

'findfile._args = Namespace(debug = False)'做了竅門。謝謝。 – sPirc 2012-02-06 10:11:27

+0

@sPirc:對不起,你必須處理那個難看的'findfile.py',所以我猜想任何破解都是合法的。但我很高興聽到你解決了你的問題。你可能想接受這個答案*(左邊的複選標記)* :) – 2012-02-06 10:25:31

相關問題