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
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"]
to file:
open(logFile, "w") do io
for thing in thingsToLog
write(io, @sprintf("%s = %s\n", thing, eval(thing)))
end
end
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 asto avoid having through
parse
at all. Usually, it's both easier and safer to pass quoted ASTs like this (in this case, symbols) directly toeval
; 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).A few more words of caution when it comes to
eval
: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:which prints
For more details, see this section in the
Debug
package readme.Call
parse
on the string first, then pass the resulting AST toeval
:eval(parse("a"))
. Optionally you can pass a module toeval
to have the expression be evaluated in a certain context (seeeval
).