2016-01-31 21 views
0

我正在编写的脚本的一部分需要定义新功能,并在执行过程中使其可用。该函数定义好了,但是当我尝试使用它,我得到一个错误:如何在脚本运行时创建并执行函数/方法?

Code execution function works! 
(defn -testfunc- [] (print "Self-execution works!")) 
(-testfunc-) 
Traceback (most recent call last): 
    File "/usr/bin/hy", line 9, in <module> 
    load_entry_point('hy==0.11.0', 'console_scripts', 'hy')() 
    File "/usr/lib/python3/dist-packages/hy/cmdline.py", line 347, in hy_main 
    sys.exit(cmdline_handler("hy", sys.argv)) 
    File "/usr/lib/python3/dist-packages/hy/cmdline.py", line 335, in cmdline_handler 
    return run_file(options.args[0]) 
    File "/usr/lib/python3/dist-packages/hy/cmdline.py", line 210, in run_file 
    import_file_to_module("__main__", filename) 
    File "/usr/lib/python3/dist-packages/hy/importer.py", line 78, in import_file_to_module 
    eval(ast_compile(_ast, fpath, "exec"), mod.__dict__) 
    File "code-trace.hy", line 41, in <module> 
    (for [line testfunc] (print line) (exec-code line)) 
    File "code-trace.hy", line 33, in exec_code 
    (eval (apply read [] {"from_file" (.StringIO io str)}))) 
    File "/usr/lib/python3/dist-packages/hy/importer.py", line 126, in hy_eval 
    return eval(ast_compile(expr, "<eval>", "eval"), namespace) 
    File "<eval>", line 1, in <module> 
NameError: name '_testfunc_' is not defined 

回答

0

这看起来像一个命名空间的问题:在

(import io) 

(defn exec-code [str] 
     (eval (apply read [] {"from_file" (.StringIO io str)}))) 

(setv ectest "(print \"Code execution function works!\")") 
(exec-code ectest) 

(setv testfunc []) 
(.append testfunc "(defn -testfunc- [] (print \"Self-execution works!\"))") 
(.append testfunc "(-testfunc-)") 
(for [line testfunc] (print line) (exec-code line)) 

结果。 eval在我认为的隔离命名空间中工作,所以第二个调用对第一个调用一无所知。

试试这个:

(defn exec-code [str] 
    (eval (apply read [] {"from_file" (.StringIO io str)}) (globals))) 

指定的命名空间是全局。这输出:

Code execution function works! 
(defn -testfunc- [] (print "Self-execution works!")) 
(-testfunc-) 
Self-execution works! 

对我来说。

相关问题