0

我正在制作的脚本的一部分要求在执行期间定义新函数并使其可用。该函数定义为 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
4

1 回答 1

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!

为了我。

于 2016-04-24T18:50:02.390 回答