如何评估字符串/将字符串转换为 Expr

Phu*_*uoc 4 julia

有没有一种方法可以将字符串转换为 Expr?我尝试了以下方法,但它不起作用:

julia> convert(Expr, "a=2")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Expr
This may have arisen from a call to the constructor Expr(...),
since type constructors fall back to convert methods.

julia> Expr("a=2")
ERROR: TypeError: Expr: expected Symbol, got String
 in Expr(::Any) at ./boot.jl:279
Run Code Online (Sandbox Code Playgroud)

bra*_*der 10

parse不再在这里工作了。现在你需要Meta.parse

eval(Meta.parse("a = 2"))
Run Code Online (Sandbox Code Playgroud)

(正如 Markus Hauschel 在评论中指出的那样。)