在 Julia 脚本中,你能判断脚本是被导入还是直接执行的吗? [英] Within a Julia script, can you tell whether the script has been imported or executed directly?

查看:17
本文介绍了在 Julia 脚本中,你能判断脚本是被导入还是直接执行的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 中的一个常见约定是将脚本的主要功能构造如下,因此它既可以作为脚本直接运行,也可以在导入时不执行 main() 导入:

A common convention in python is to structure the main functionality of a script as follows, so it can be both run as a script directly or imported without executing main() at the time of import:

def main():
    do_stuff()

if __name__ == '__main__':
    main()

在 Julia 中是否设置了类似的变量,以便脚本可以知道它是使用 require("script.jl") 导入还是直接执行?

Is there a similar variable that gets set in Julia, so that the script can be aware of whether it was imported using require("script.jl") or executed directly?

例如,假设我有两个脚本,a.jlb.jl,以及一个 magic_function(),其行为如下如下:

For example, say I have two scripts, a.jl and b.jl, along with a magic_function() that behaves as follows:

a.jl:

println("Did we execute a.jl directly? ", magic_function())

b.jl:

require("a.jl")

执行以下命令会导致...

Executing the following commands results in ...

> julia a.jl
Did we execute a.jl directly? true
> julia b.jl
Did we execute a.jl directly? false

目前的Julia发行版中是否存在magic_function()这样的函数?

Does a function like magic_function() exist in the current distribution of Julia?

推荐答案

官方 Julia 文档建议:

Official Julia doc suggests this:

if abspath(PROGRAM_FILE) == @__FILE__

    # do something only this file is executed. 
    do_something()

end

do_something函数只在代码执行时执行,从其他代码导入代码时不执行.

The do_something function is only executed when the code is executed, not when the code is imported from other codes.

Ref:如何检查当前文件是否作为主脚本运行?"https://docs.julialang.org/en/v1/manual/faq/#How-do-I-check-if-the-current-file-is-作为主脚本运行?-1

Ref:"How do I check if the current file is being run as the main script?" https://docs.julialang.org/en/v1/manual/faq/#How-do-I-check-if-the-current-file-is-being-run-as-the-main-script?-1

这篇关于在 Julia 脚本中,你能判断脚本是被导入还是直接执行的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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