我在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()');
因爲我的主程序只能發送字符串,所以我必須使用一個字符串。 – 2012-03-04 07:01:54
你確定嗎? - 這看起來像一個任意的約束。我不想成爲那個人:) - 但你可以嘗試避免這種粘性的東西。此外,如果你給一個字符串「test」,cron執行者仍然需要找到相應的函數。因此,如果你的主程序與cron執行程序分離,以至於你只能傳遞字符串,我懷疑,指定的函數可以在執行程序的命名空間中訪問。 – sleeplessnerd 2012-03-04 07:11:47
不幸的是,我寫的程序是封閉源代碼。我正在製作一個tcp代理服務器,並且需要在旅途中解釋這些消息。 雖然這個任務只會被內部函數和其他解釋使用,所以你可能是正確的解決工作的可能性。我會研究它。乾杯。 – 2012-03-04 07:16:54