[英]How to run parallel python scripts from java using the ProcessBuilder
this is my first question here. 这是我的第一个问题。 I am trying to run parallel python scripts (that is multiple instances of a same script) from java periodically using the ScheduledThreadPoolExecutor.
我正在尝试使用ScheduledThreadPoolExecutor从Java定期运行并行python脚本(即同一脚本的多个实例)。 What i tried to do was using the ProcessBuilder class.
我试图做的是使用ProcessBuilder类。 To test the concept i have put first script into infinite loop while the second writes something to file and exits.
为了测试这个概念,我将第一个脚本置于无限循环中,而第二个脚本则将一些内容写入文件并退出。 Python scripts i need to make should be identical to each other so i tried to run these two from multiple instaces of a same class that implements runnable.
我需要制作的Python脚本应该彼此相同,因此我尝试从实现可运行的同一类的多个实例中运行这两个脚本。
However the second script never starts. 但是,第二个脚本永远不会启动。 I managed to solve this by creating many classes that have exactly same runnable.
我设法通过创建许多具有完全相同的可运行类的方法来解决此问题。 But it seems highly impractical to have 10-20 classes that are same.
但是,拥有10至20个相同的类似乎非常不切实际。 So can i do this somehow within one runnable?
那么我可以在一个可运行的时间内执行此操作吗? Here is the code that shows how i tried to run scripts using the ProcessBuilder:
这是显示我如何尝试使用ProcessBuilder运行脚本的代码:
public class TestScripts{
public static void main(String[] args){
ScheduledThreadPoolExecutor threadPool = new ScheduledThreadPoolExecutor(2);
threadPool.scheduleAtFixedRate(new MyTask1(), 1,2, TimeUnit.SECONDS);
threadPool.scheduleAtFixedRate(new MyTask1(), 1,2, TimeUnit.SECONDS);
}
}
class MyTask1 implements Runnable{
public void run(){
System.out.println("Task1 is running");
ProcessBuilder processBuilder = new ProcessBuilder("C:\\Python27\\python.exe",
"C:\\Python27\\test.py");
ProcessBuilder processBuilder2 = new ProcessBuilder("C:\\Python27\\python.exe",
"C:\\Python27\\test2.py");
processBuilder.redirectOutput(Redirect.INHERIT);
try {
Process process = processBuilder.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Process process2 = processBuilder.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There is a typo in the line starting 2nd process: 在开始第二个过程的一行中有一个错字:
Process process2 = processBuilder.start();
should be of course: 当然应该是:
Process process2 = processBuilder2.start();
Besides you are scheduling 2 tasks, where each task starts 2 processes. 此外,您还计划2个任务,每个任务开始2个进程。 So each 2 seconds there are 4 processes started (2x test.py, 2x test2.py).
因此,每2秒就会启动4个进程(2x test.py,2x test2.py)。 If I understand correctly what you're trying to do, scheduling only one
MyTask1
should be enough. 如果我正确理解了您要执行的操作,则仅安排一个
MyTask1
就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.