2016-10-13 40 views
3

需要下一種情況的幫助。我想通過在打印小完工報告中的功能與命令執行的名稱和ellapsed時間等,以實現調試模式在我的腳本:Python:將變量傳遞給多個函數調用的好方法

def cmd_exec(cmd): 
    if isDebug: 
     commandStart = datetime.datetime.now() 
     print commandStart 
     print cmd 
    ... 
    ... exucuting commands 
    ... 
    if isDebug: 
     print datetime.datetime.now() - command_start 
    return 

def main(): 
    ... 
    if args.debug: 
     isDebug = True 
    ... 
    cmd_exec(cmd1) 
    ... 
    cmd_exec(cmd2) 
    ... 

如何isDebug變量簡單地傳遞給函數? 我應該使用「全球isDebug」嗎?

因爲

... 
    cmd_exec(cmd1, isDebug) 
    ... 
    cmd_exec(cmd2, isDebug) 
    ... 

看起來很糟糕。請幫我找到更優雅的方式。

回答

1

您可以使用模塊來創建共享的變量。這比全局更好,因爲它只會影響專門查找變量的代碼,並不會污染全局名稱空間。它還可以讓你定義一些東西,而不需要你的主模塊知道它。

這是可行的,因爲模塊是Python中的共享對象。每個import獲取對同一個對象的引用,並且對該模塊內容的修改立即得到共享,就像全局一樣。

my_debug.py:

isDebug = false 

main.py:

import my_debug 

def cmd_exec(cmd): 
    if my_debug.isDebug: 
     # ... 

def main(): 
    # ... 
    if args.debug: 
     my_debug.isDebug = True 
+0

感謝您提供解決方案。問題是我經常切換模式。只需在腳本的開頭添加'-d'選項,swich調試模式更方便 –

+0

@VimimK我不確定什麼是異議。我在這裏呈現的代碼位直接從您的問題中複製。 –

+0

是的,我的意思是,打開/關閉調試模式,我將需要每次編輯_my_debug.py_文件 –

2

isDebug是適用於函數cmd_exec的應用的狀態。聽起來像是一個班級對我的用例。

class CommandExecutor(object): 

    def __init__(self, debug): 
     self.debug = debug 

    def execute(self, cmd): 
     if self.debug: 
      commandStart = datetime.datetime.now() 
      print commandStart 
      print cmd 
     ... 
     ... executing commands 
     ... 
     if self.debug: 
      print datetime.datetime.now() - command_start 

def main(args): 
    ce = CommandExecutor(args.debug) 
    ce.execute(cmd1) 
    ce.execute(cmd2) 
+0

感謝您的答覆。你能解釋一件事嗎?如果_cmd_exec_函數不僅從_main_中調用,而且還從許多其他函數中調用?這是否意味着我將被迫使用類實例而不是一個變量操作 –

2

Python有一個內置的__debug__變量可能是有用的。

if __debug__: 
    print 'information...' 

當你運行你的程序爲python test.py__debug__True。如果你運行它作爲python -O test.py,它將是False

,我在我的項目做的另一種選擇是在文件的開頭設置一個全局DEBUG變種,導入後:

DEBUG = True 

然後,您可以在該函數的範圍內引用這個DEBUG變種。

0

專門爲此,我將使用泛音/鑽營,基本上填充前的變量。

import sys 
from functools import partial 
import datetime 

def _cmd_exec(cmd, isDebug=False): 
    if isDebug: 
     command_start = datetime.datetime.now() 
     print command_start 
     print cmd 

    else: 
     print 'isDebug is false' + cmd 

    if isDebug: 
     print datetime.datetime.now() - command_start 
    return 

#default, keeping it as is... 
cmd_exec = _cmd_exec 

#switch to debug 
def debug_on(): 
    global cmd_exec 

    #pre-apply the isDebug optional param 
    cmd_exec = partial(_cmd_exec, isDebug=True) 


def main(): 
    if "-d" in sys.argv: 
     debug_on() 

    cmd_exec("cmd1") 
    cmd_exec("cmd2") 

main() 

在這種情況下,我檢查-d在命令行打開調試模式,我用isDebug = True創建一個新的功能做在函數調用填入預先isDebug。

我想即使是其他模塊也會看到這個修改過的cmd_exec,因爲我在模塊級替換了這個函數。

輸出:

jluc @ $探索PY test_so64.py
isDebug is falsecmd1 isDebug is falsecmd2

jluc @ $探索PY test_so64.py -d
2016-10-13 17:00:33.523016 cmd1 0:00:00.000682 2016-10-13 17:00:33.523715 cmd2 0:00:00.000009