2012-03-04 65 views
0

我在python中編寫了一個簡單的測試程序作爲我的更大程序的一部分,但是我想將一個子函數名稱傳入主函數,所以主函數可以運行子功能。Python:exec「function()」

如:

import datetime; 

def cronjob(repeat, interval, task): 
    if (str(repeat) == 'inf'): 
     repeat = 99999999999999999999; 
    position = 0; 
    interval = datetime.timedelta(seconds=interval); 
    x = datetime.datetime.now() 
    while not (position >= repeat): 
     while (datetime.datetime.now() - x < interval): 
      pass; 
     x = datetime.datetime.now(); 
     position += 1; 
     exec task; 

def test(): 
    print "hello"; 

cronjob(10, 0.1, 'test'); 

編輯:已經解決了這一點,但因爲沒有被列在這裏,讓我告訴你如何做到這一點的情況下,其他人需要它。

我擺弄eval()和exec,並嘗試只是eval(任務)。沒有拋出錯誤,所以我試着打印評估(任務),果然,它列出了函數的內存地址[即test()]。最後,我用eval(任務);然後調用該函數。以下是修復此問題的代碼:

import datetime; 

def cronjob(repeat, interval, task): 
    if (str(repeat) == 'inf'): 
     repeat = 99999999999999999999; 
    position = 0; 
    interval = datetime.timedelta(seconds=interval); 
    x = datetime.datetime.now() 
    while not (position >= repeat): 
     while (datetime.datetime.now() - x < interval): 
      pass; 
     x = datetime.datetime.now(); 
     position += 1; 
     eval(task); 

def test(): 
    print "hello"; 

cronjob(10, 0.1, 'test()'); 

回答

2

爲什麼不將函數對象本身傳遞給調度器?

測試是一個對象,也可以用作參數!

def test(): 
    print "test" 

def exe(func): 
    func() 

exe(test) 
+0

因爲我的主程序只能發送字符串,所以我必須使用一個字符串。 – 2012-03-04 07:01:54

+0

你確定嗎? - 這看起來像一個任意的約束。我不想成爲那個人:) - 但你可以嘗試避免這種粘性的東西。此外,如果你給一個字符串「test」,cron執行者仍然需要找到相應的函數。因此,如果你的主程序與cron執行程序分離,以至於你只能傳遞字符串,我懷疑,指定的函數可以在執行程序的命名空間中訪問。 – sleeplessnerd 2012-03-04 07:11:47

+0

不幸的是,我寫的程序是封閉源代碼。我正在製作一個tcp代理服務器,並且需要在旅途中解釋這些消息。 雖然這個任務只會被內部函數和其他解釋使用,所以你可能是正確的解決工作的可能性。我會研究它。乾杯。 – 2012-03-04 07:16:54

0

我相信,因爲函數是對象,你可以通過名字傳遞一個到「控制」功能,所以你不需要exec調用(通常用於動態代碼執行)。

例如

def foo(a_number, a_function): 
    print a_number 
    a_number += 1 
    a_function(a_number) 

def bar(another_number): 
    print another_number 

foo(5, bar) 

應該產生的輸出:
5
6

0

在情況下,如果你是絕對相信你想從一個字符串導出功能,您可能需要使用一個字典作爲一個映射從字符串到功能如下:

dispatcher = {'dothis': module1.do_this, 
       'dothat': module2.to_that} 

def foo(fun): 
    fun(arg1, arg2) 

def bar(action): 
    fun = dispatcher.get(action) 
    if fun: 
     foo(fun) 

這樣會更安全(因爲動作可能來自ou tside),並提供內部代碼結構與外部API更好的解耦。

相關問題