在groovy中如何获取运行脚本的路径? [英] How do you get the path of the running script in groovy?
问题描述
我正在编写一个 groovy 脚本,我希望通过存储在同一文件夹中的属性文件对其进行控制.但是,我希望能够从任何地方调用这个脚本.当我运行脚本时,它总是根据它的运行位置而不是脚本所在的位置查找属性文件.
I'm writing a groovy script that I want to be controlled via a properties file stored in the same folder. However, I want to be able to call this script from anywhere. When I run the script it always looks for the properties file based on where it is run from, not where the script is.
如何从脚本内部访问脚本文件的路径?
How can I access the path of the script file from within the script?
推荐答案
从 Groovy 2.3.0 开始,@SourceURI
注释可用于使用脚本位置的 URI 填充变量.然后可以使用此 URI 获取脚本的路径:
As of Groovy 2.3.0 the @SourceURI
annotation can be used to populate a variable with the URI of the script's location. This URI can then be used to get the path to the script:
import groovy.transform.SourceURI
import java.nio.file.Path
import java.nio.file.Paths
@SourceURI
URI sourceUri
Path scriptLocation = Paths.get(sourceUri)
请注意,这仅在 URI 是 file:
URI(或安装了 FileSystemProvider),否则为 FileSystemNotFoundException 将由Paths.get(URI)
调用.特别是,某些 Groovy 运行时(例如 groovyshell 和 nextflow)会返回 data:
URI,该 URI 通常与已安装的 FileSystemProvider
不匹配.
Note that this will only work if the URI is a file:
URI (or another URI scheme type with an installed FileSystemProvider), otherwise a FileSystemNotFoundException will be thrown by the Paths.get(URI)
call. In particular, certain Groovy runtimes such as groovyshell and nextflow return a data:
URI, which will not typically match an installed FileSystemProvider
.
这篇关于在groovy中如何获取运行脚本的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!