0

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 ?

Malik
  • 207
  • 1
  • 2
  • 14
  • Look at this: http://stackoverflow.com/questions/8898765/calling-python-in-java – ptitpoulpe May 06 '15 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 May 06 '15 at 12:12

3 Answers3

2

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
lsowen
  • 3,728
  • 1
  • 21
  • 23
  • The problem is that it's for users, so they won't use a command line interface. I need the java program itself to call for an execution of the python program. – Malik May 06 '15 at 12:14
0

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.

Community
  • 1
  • 1
  • I updated my question to go along with your 2nd answer, can you take a look please ? Thank you ! – Malik May 06 '15 at 12:39
0

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248