matplotlib - Load Julia modules on demand
问题描述
I I have a very simple question. Is it possible to load modules on demand in Julia. That is, can the modules be loaded when they are actually needed instead of being loaded at "parse-time" at the top level.
The use case scenario I have in mind is that I have some set of code that is able to do some plotting using PyPlot, but code is far from always executed.
At the moment this means that I have at top level a statement like using PyPlot
, which takes quite a load of time to load.
(Yes i know: One should not restart Julia to often, bla bla bla... but nevertheless this is a point of annoyance)
Is there a way to ensure that PyPlot is only loaded is if is actually needed?
The simplest idea would have been to include the using PyPlot
inside the function that actually do the plotting
function my_plot()
using PyPlot
plot(1:10,1:10)
end
but this results in a syntax error:
ERROR: syntax: "using" expression not at top level
So, is there another way to achieve this?
解决方案
“using”语句在遇到代码行时运行,并且不必位于文件顶部。它确实需要在全局范围内,这意味着加载“using”的模块中的变量将在“using”语句执行后可供程序中的所有函数使用,而不仅仅是在函数的局部作用域。
如果您将 using 语句作为 Julia eval 语句中的表达式调用,则在 Julia 中的“eval”语句中执行的所有代码都会在全局范围内自动执行,即使 eval 在函数的本地范围内按语法调用也是如此。所以如果你使用宏@eval
function my_plot()
@eval using PyPlot # or without the macro, as eval(:(using PyPlot))
plot(1:10,1:10)
end
这就像使用 PyPlot 在函数外部完成一样,因此避免了语法错误。
推荐阅读
- xcode - 是否可以扩展 MacOS Terminal.app?
- xml - 如何为xml中的每个节点添加相同的前缀?
- intellij-idea - 如何在 IntelliJ Idea 的代码样式设置中为循环内部配置不同的间距规则?
- excel - 如何在 Powershell 脚本中使用 VBA 代码
- html - 如何将网页屏幕水平分成3等份?
- spring - Spring Batch 两个不同结构的文件
- javascript - 手机上的图像拖动故障
- hyperlink - 如何运行将单击并打开网页上所有链接的 Applescript?
- sql - SQL 查询用户设置行号和最后日期
- java - JPA 和二级缓存。缓存未开启