[英]Access string variable from bash in jenkinsfile groovy script
[英]Groovy access script variable from application
需要訪問groovy腳本文件中定義的變量
在使用GroovyShell
執行腳本之前
但是,我收到錯誤:
groovy.lang.MissingPropertyException: No such property: _THREADS for class: Test1
//Test1.groovy
_THREADS=10;
println("Hello from the script test ")
//scriptRunner.groovy
File scriptFile = new File("Test1.groovy");
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (scriptFile);
def thread = script.getProperty('_THREADS'); // getting ERROR --
// No such property: _THREADS for class: Test1
//-------
//now run the threads
script.run()
您必須在獲取屬性/綁定之前運行腳本
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (''' _THREADS=10 ''')
script.run()
println script.getProperty('_THREADS')
嘗試在 groovy 控制台中打開AST Browser (Ctrl+T)
以獲取此代碼:
_THREADS=10
您將看到大約以下生成的 class:
public class script1663101205410 extends groovy.lang.Script {
public java.lang.Object run() {
_THREADS = 10
}
}
其中_THREADS = 10
將屬性分配給綁定
但是,可以將 _THREADS 定義為 function,然后無需運行腳本即可訪問它。
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (''' def get_THREADS(){ 11 } ''')
println script.getProperty('_THREADS')
解析后可以訪問使用@Field
修飾符值的解決方案
import groovy.transform.Field
@Field _THREADS=10
File scriptFile = new File("Test1.groovy");
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (scriptFile);
def thread = script.getProperty('_THREADS'); //value is accessible
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.