簡體   English   中英

如何在 Groovy 中獲取腳本名稱

[英]How to get the script name in Groovy

如何獲取在 Groovy 中執行的腳本的名稱?

它不是命令行參數,因此args數組沒有任何幫助。

您可以按如下方式獲取當前腳本名稱。

def scriptName = this.class.getName()
println "Script FQCN : " + scriptName

它將使用其包名稱--FQCN (完全限定類名)打印出腳本的名稱(它只是一個類)。

如果您只想要腳本名稱而不是包,則可以使用

println "Script Simple Name : " + this.class.getSimpleName()

我在支持類中為很多腳本執行此操作,因此itsraghz的答案對我不起作用。

如果您使用腳本調用的支持類中的this.class或getClass(),您將獲得支持類的名稱,而不是腳本的名稱。 每次使用時都要獲取腳本的名稱:

// Get the executed script as a (java) File
File scriptFile = new File(getClass().protectionDomain.codeSource.location.path)

// This holds the file name like "myscript.groovy"
def scriptName = scriptFile.getName()

// strip the extension to get "myscript"
def withoutExt = scriptName.take(scriptName.lastIndexOf('.'))

如果應用於腳本本身,上述解決方案是完美的。 有時需要從腳本調用的其他文件或類中知道腳本名稱。

例如腳本script1.groovy調用SomeClass 這個SomeClass也可以找到腳本的名稱。 單線解決方案是

StackTraceUtils.deepSanitize(new Exception()).getStackTrace().last().getFileName()

看下面的例子:

script1.groovy:

import SomeClass
def someInst = new SomeClass()

SomeClass.groovy:

import org.codehaus.groovy.runtime.StackTraceUtils
class SomeClass {
   String scriptName = StackTraceUtils.deepSanitize(new Exception()).getStackTrace().last().getFileName().replaceAll(/\.groovy/, '')
   println "My calling script is '$scriptName'"
}

output:

My calling script is 'script1'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM