有没有办法在 Autoit 脚本中查找当前文件是否包含或它是否自行运行



我的意思是像 php 中的 get_included_files(); 或 javascript 中的 Error().stack; 或 bash 中的$BASH_SOURCE数组?

我只在宏(https://www.autoitscript.com/autoit3/docs/macros.htm(中找到@ScriptFullPath@ScriptName

检查@ScriptName是否与当前脚本的名称匹配。如果没有,您的脚本已包含在其他内容中。如果包含的脚本作为独立脚本运行,我使用此方法运行单元测试。我将以下代码添加到 included_script.au3 的末尾:

; unit test code
If @ScriptName == "included_script.au3" Then
    MsgBox(0, "Unit Test", "Running unit test...", 3)
    test()
    Exit
EndIf
Func test()
    ; no test defined
EndFunc

当包含在"main.au3"文件中时,@ScriptName将设置为"main.au3",并且不会test()运行。

可以使用全局变量实现该功能。 说$includeDepth. $includeDepth应在任何#include之前递增 1,之后应递减 1。 如果$includeDepth 0,则代码不作为#include的一部分运行。 例如:

Global $includeDepth
$includeDepth+= 1
#include <MyScript1.au3>
#include <MyScript2.au3>
$includeDepth-= 1
; Declarations, functions, and initializations to be run in both "include" and "non-include" modes
If $includeDepth <= 0 Then
    ; Code for when in "non-include" mode
EndIf

但是,您需要在此用法中保持一致。 但是,只要库#include不包含您自己的脚本(或执行此检查的脚本(,就无需修改它们。 从这个角度来看,也没有必要在包含库#include时增加/减少$includeDepth。 但是,它不会造成伤害,并且可以加强练习。

最新更新