I want to know what is the easiest way to pass a String from my Java program to my Python program. The reason is that I use boilerpipe to extract some text from the web, then analyse it through my Java program, but I also have to make some semantic searchs using pattern.en, which is only available for python.
I don't need to get results back from my python program, just that my Python program can get the String.
I first thought about letting my python program listen to a .txt file, while java feeds it with the String, but I think it'll be too hard to make.
I'm on Windows 7, and my Python version is 2.7.9.
EDIT : I think I haven't been very clear actually. Ideally, I'd want my java code to run my python program which would have recieved the string.
Graciela Runolfsdottir's 2nd answer would maybe do the trick, if I can make something like that :
String s = "string to analyse"
FileUtils.writeStringToFile(new File("test.txt"), s);
Then execute it with : python analyzer.py test.txt, but I don't know how to call this command from java. Is it possible ?
-
Look at this: stackoverflow.com/questions/8898765/calling-python-in-javaptitpoulpe– ptitpoulpe2015年05月06日 12:07:29 +00:00Commented May 6, 2015 at 12:07
-
@Jägermeister Because I should let the python program listening to the file, then dealing with access problems, if java tries to write while python is reading, etc.Malik– Malik2015年05月06日 12:12:13 +00:00Commented May 6, 2015 at 12:12
3 Answers 3
The easiest way to accomplish this (and historically the "canonical" way) would be to write the string to stdout with the source program (the Java program in your case) and read from stdin with the sink program (the python program).
To link the input/output, you could use "Command Redirection", specifically the pipe:
java -jar source_program.jar | python sink_program.py
1 Comment
You can pass String through:
- command line argument (it should not to be long and must be escaped)
- file (just save string to file and pass it file name to Python application)
- STDIN (output your string to STDIN of your Python program)
I think the last way is simple in implementation and you should choose it.
1 Comment
Different approach: try using jython. That might you to actually run python code "within" the context of your JVM.
Or if you are really concerned about having a "solid" solution based on a profound architecture; consider using a message bus; like ActiveMQ which has clients for both Java and Python.