没有任何选项涉及您尝试执行"python3 "+script
,以及等效项,将会起作用。script
is an InputStream
,不是文件系统上的路径,因此只需将其与String
不会给你任何有意义的东西。此外,由于您的脚本不在自己的文件中,并且 python 解释器没有简单的方法来提取它,因此简单地像这样调用它是行不通的。
但是,您可以做的是执行
python3 -
The -
这里的选项(至少在类似 BSD 的系统上)意味着“从标准输入读取,并将其解释为脚本”。然后,在Java端,您可以将jar打包的资源作为流读取,并将其通过管道传输到python进程的标准输入。
有关为资源选择正确路径的详细信息,请参阅如何确定 JavaFX 应用程序所需的 FXML 文件、CSS 文件、图像和其他资源的正确路径?.
以下内容(其中脚本简单地放置在与类相同的包中)对我有用:
PythonRunner.java:
package example.python;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class PythonRunner {
public static void main(String[] args) throws Exception {
String pythonInterpreter = "/usr/bin/python3" ; // default
if (args.length > 0) {
pythonInterpreter = args[0] ;
}
InputStream script = PythonRunner.class.getResourceAsStream("script.py");
Process pythonProcess = new ProcessBuilder(pythonInterpreter, "-")
.start();
// This thread reads the output from the process and
// processes it (in this case just dumps it to standard out)
new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(pythonProcess.getInputStream()))) {
for (String line ; (line = reader.readLine()) != null ;) {
System.out.println(line);
}
} catch (IOException exc) {
exc.printStackTrace();
}
}).start();
// read the script from the resource, and pipe it to the
// python process's standard input (which will be read because
// of the '-' option)
OutputStream stdin = pythonProcess.getOutputStream();
byte[] buffer = new byte[1024];
for (int read = 0 ; read >= 0 ; read = script.read(buffer)) {
stdin.write(buffer, 0, read);
}
stdin.close();
}
}
脚本.py:
import sys
for i in range(10):
print("Spam")
sys.exit(0)
清单.MF
Manifest-Version: 1.0
Main-Class: example.python.PythonRunner
日食布局:
jar内容和运行结果:
$ jar tf runPython.jar
META-INF/MANIFEST.MF
example/python/PythonRunner.class
example/python/script.py
$ java -jar runPython.jar
Spam
Spam
Spam
Spam
Spam
Spam
Spam
Spam
Spam
Spam
$