4

我需要在运行时检索 Groovy 2.3 中脚本文件的完整路径。实际上,我遇到的问题与此处描述的问题相同:在运行时获取 groovy 源文件的路径

我的脚本是否可以从 GroovyShell 执行。

我的脚本位于:

C:\users\myname\documents\scripts\myscript.groovy

=> 我只想在运行时检索此路径。

如果我使用被接受的解决方案:

println new File(".").absolutePath

我得到的实际上是:

C:\groovy-2.3.7\.

这是 groovy 主文件夹。这是不正确的。另一个建议的答案即:

URL scriptUrl = getClass().classLoader.resourceLoader.loadGroovySource(getClass().name)

仅当我的脚本位于类路径中,或者在 groovy 启动时使用 groovy-starter.conf 中的加载指令加载它时才有效。否则返回null。我可以使用这种方法,但它并不令人满意,因为它就像传递参数一样,这里的目标是用户能够从任何地方执行脚本而无需修改或配置。

我也红了这个专注于这个问题的JIRA: JIRA-1642

解决方案似乎使用了为此目的创建的@SourceURI 注释。问题是我无法让它工作。我尝试执行如下所示的代码用法:SourceURI

@groovy.transform.SourceURI def sourceURI
assert sourceURI instanceof java.net.URI
path = sourceURI.toString()
println "path = $path"

我得到的是(groovy 2.3.7)不是路径而是源代码:

path = data:,@groovy.transform.SourceURI%20def%20sourceURI%0A%0A%20assert%20sourceURI%20instanceof%20java.net.URI%0Apath%20=%20sourceURI.toString()%0Aprintln%20%22path%20=%20$path%22

如何使用@SourceURI 注释来检索脚本文件的路径?

4

2 回答 2

5

我正在寻找与您相同的脚本路径信息。我注意到在通过 shell 运行以下命令时:

@groovy.transform.SourceURI def sourceURI
assert sourceURI instanceof java.net.URI
sourceURI.properties.each { i -> 
    println i
}

我得到以下有用的结果(注意路径中的值):

rawAuthority=null
opaque=false
scheme=file
rawQuery=null
port=-1
rawUserInfo=null
path=/home/ttresans/GroovyScripts/TestSourceURI.groovy
class=class java.net.URI
absolute=true
schemeSpecificPart=/home/ttresans/GroovyScripts/TestSourceURI.groovy
rawPath=/home/ttresans/GroovyScripts/TestSourceURI.groovy
query=null
fragment=null
host=null
authority=null
rawFragment=null
userInfo=null
rawSchemeSpecificPart=/home/ttresans/GroovyScripts/TestSourceURI.groovy

但是,如果我将相同的内容粘贴到 GroovyConsole 中,我会得到以下信息:

rawAuthority=null
opaque=true
scheme=data
rawQuery=null
port=-1
rawUserInfo=null
path=null
class=class java.net.URI
absolute=true
schemeSpecificPart=,@groovy.transform.SourceURI def sourceURI
assert sourceURI instanceof java.net.URI
sourceURI.properties.each { i -> 
    println i
}

rawPath=null
query=null
fragment=null
host=null
authority=null
rawFragment=null
userInfo=null
rawSchemeSpecificPart=,@groovy.transform.SourceURI%20def%20sourceURI%0Aassert%20sourceURI%20instanceof%20java.net.URI%0AsourceURI.properties.each%20%7B%20i%20-%3E%20%0A%20%20%20%20println%20i%0A%7D%0A

这是在 Ubuntu 上的 Groovy 2.3.9 上。

所以看起来 GroovyConsole 的启动可能是个问题,但注解确实会产生所需的路径。

于 2015-01-05T18:55:42.960 回答
1

Have you tried going through the protection domain, like this:

How do you get the path of the running script in groovy?

于 2014-10-07T21:03:54.587 回答