【发布时间】:2012-03-04 06:39:44
【问题描述】:
我正在用 python 编写一个简单的测试程序作为我更大程序的一部分,但我想将一个子函数名称传递给主函数,以便主函数可以运行子函数。
例如:
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(task)。没有抛出错误,所以我尝试了 print eval(task),果然,它列出了函数的内存地址 [即 test()]。最后,我使用了 eval(task);然后调用该函数。以下是修复此问题的代码:
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()');
【问题讨论】:
标签: python string function exec eval