在Julia脚本中,您能否确定该脚本是否已导入或直接执行? [英] Within a Julia script, can you tell whether the script has been imported or executed directly?
问题描述
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.jl
和b.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?
推荐答案
虽然isinteractive()
使您可以识别REPL是否在命令行上运行/是否已导入其他代码中,但无法获得与以下代码完全相同的功能Python的if __name__ == '__main__'
.
While isinteractive()
will let you discern the REPL from being run on the commandline/imported into other code, there is no way to get exactly the same functionality as Python's if __name__ == '__main__'
.
这似乎没有计划作为功能.请参阅邮件列表上的讨论. (从2013年6月开始)
This does not seem to be planned as a feature. See this discussion on the mailing list. (from June 2013)
这篇关于在Julia脚本中,您能否确定该脚本是否已导入或直接执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!