4

我想让我的 groovy 脚本可移植,并在第一行插入:

#!/usr/bin/env groovy

当我在其目录之外运行脚本时出现问题,它找不到库。我来自 python 世界,python 中的所有导入都解析了相对脚本的路径。在 groovy 中,我似乎必须指定 -classpath 但我不能在第一个 #! 线。

任何建议如何解决它?

4

1 回答 1

10

If the libraries are stored in a Maven repository that is accessible wherever you want to run it, one solution would be to use Grape to grab the libraries.

This provides several benefits:

  1. You don't have to worry about the classpath at all
  2. You don't have to distribute the libraries — just make sure Groovy is available on the client
  3. Libraries are downloaded just once, so even if you upgrade the application, you only have to redistribute the .groovy file.

A simple example:

#!/usr/bin/env groovy

@Grab(group='commons-io', module='commons-io', version='2.3')
import org.apache.commons.io.FileUtils

... use FileUtils like normal ...

There's a lot of existing libraries available on mvnrepository.com already.

Even if you have non-public libraries, it's relatively easy to put your own libraries into a local / private repository.

于 2012-05-24T07:49:28.510 回答