如何在脚本运行时创建和执行函数/方法?

时间:2016-01-31 21:39:57

标签: hy

我制作的脚本的一部分要求在执行期间定义新功能并使其可用。该函数定义了OK,但是当我尝试使用它时出现错误:

(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))

结果:

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

1 个答案:

答案 0 :(得分:0)

这看起来像命名空间问题。我认为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!

对我来说。