简体   繁体   English

并行运行来自不同编程语言的两段代码

[英]Run two pieces of code from different programming language in parallel

有什么方法可以在一个应用程序中并行运行来自 python 的函数和来自 java 的函数,并获取每个函数的结果来执行另一个进程?

There are at least three ways to achieve that. 至少有三种方法可以实现这一目标。

a) You could use java.lang.Runtime (as in Runtime.getRuntime().exec(...) ) to launch an external process (from Java side), the external process being your Python script. a)您可以使用java.lang.Runtime (如Runtime.getRuntime().exec(...) )启动外部进程(从Java端开始),该外部进程就是您的Python脚本。

b) You could do the same as a), just using Python as launcher. b)您可以使用a)做相同的事情,只是使用Python作为启动器。

c) You could use some Python-Java binding, and from Java side use a separate Thread to run your Python code. c)您可以使用一些Python-Java绑定,并且从Java方面使用单独的Thread来运行Python代码。

You should probably look for jython . 您可能应该寻找jython This support Java and Python . 这支持JavaPython

The question is fairly vague and without a specific use case, but I can suggest a generic approach of writing a shell script. 这个问题很模糊,没有特定的用例,但是我可以建议编写Shell脚本的通用方法。

You could run both the Python and the Java functions if they're placed individually in separate .py and .java files, and write their outputs to temp files, so you can use the values for further computation. 如果将Python和Java函数分别放置在单独的.py和.java文件中,则可以运行它们,并将它们的输出写入临时文件,以便可以将这些值用于进一步的计算。

my-shell$ vi my_script.sh

#!/usr/bin/env bash
python python_file.py argument1 argument2 >> py-output.txt
echo "completed execution of python script." 
javac JavaFile.java
java JavaFile >> java-output.txt
echo "completed execution of java funtion."

Note : This assumes your bash script is in the same directory as your python and java files, else, just give the full path to your files. 注意 :假设您的bash脚本与python和java文件位于同一目录中,否则,只需提供文件的完整路径即可。

After you've saved the script, make it executable by typing chmod u+x my_script.sh . 保存脚本后,通过键入chmod u+x my_script.sh使其可执行。 Then, just run it, and voilà, you're done. 然后,只需运行它,然后完成。 Two .txt files with the outputs from both functions, for you to use as you please. 两个.txt文件,具有两个函数的输出,供您随意使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM