执行一个字符串? [英] Execute a string?

查看:68
本文介绍了执行一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个字符串,但是发现茱莉亚(Julia)中没有exec函数:

I wanted to execute a string, but found that there's no exec function in Julia:

a = 1
println(exec("a")) # ERROR: exec not defined

有没有办法在Julia中执行字符串?

Is there a way to execute a string in Julia?

最初的问题是我正在尝试记录变量列表:

The original problem is that I'm trying to log a list of variables:

thingsToLog = ["a", "b", "c"]

要提交:

open(logFile, "w") do io
    for thing in thingsToLog
        write(io, @sprintf("%s = %s\n", thing, eval(thing)))
    end
end

推荐答案

如上所述,您可以调用parse以从字符串创建AST,然后在该字符串上调用eval.在您的示例中,将列表创建为

As said above, you can call parse to create an AST from the string, and then call eval on that. In your example though, it seems easier to create your list as

thingsToLog = [:a, :b, :c]

避免完全通过parse.通常,将像这样的带引号的AST(在这种情况下为符号)直接传递给eval既容易又安全.如果用固定的AST集还不够的话,您还可以将AST插值到引用的AST中.(请参阅手册以了解更多详细信息).

to avoid having through parse at all. Usually, it's both easier and safer to pass quoted ASTs like this (in this case, symbols) directly to eval; you can also interpolate ASTs into quoted ASTs if it's not enough with a fixed set of ASTs (see the manual for more details).

eval时要多加注意:

  • 根据设计,它只能在全局范围内使用.
  • 这不是很快,因为它需要编译新代码.因此,最好将其保留给只需要执行一次的评估(例如评估生成的方法或类型定义),或者在速度不是很重要的时候.
  • 这可能会使代码难以理解.

关于在本地范围内的评估,阅读此线程使我意识到Debug软件包中已经包含了大多数必需的功能,因此我刚刚发布了允许此功能的更新(尽管上面的注意事项仍然适用).您要在本地范围内评估代码的函数必须用@debug_analyze宏包装.然后,您可以使用@localscope检索表示局部作用域的对象,并通过索引相应的符号从中检索局部变量的值.示例:

Regarding evaluation in local scope, reading this thread made me realize that most of the required functionality was already present in the Debug package, so I just released an update that allows this (the cautions above still apply though). The function where you want to evaluate code in local scope has to be wrapped with the @debug_analyze macro. Then you can retrieve an object representing the local scope using @localscope, and retrieve values of local variables from it by indexing with the corresponding symbols. Example:

using Debug
@debug_analyze function f(x,y,z,thingsToLog)
    s = @localscope
    for sym in thingsToLog
        println(sym, " = ", s[sym])
    end
end
f(1,2,3,[:x,:z])

可打印

x = 1
z = 3

有关更多详细信息,请参见本节Debug软件包自述文件中.

For more details, see this section in the Debug package readme.

这篇关于执行一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆