2

I am trying to invoke a python script (part of a larger python project) from a java app. I've tested and tested this, it works exactly as expected from the command line. I've even resorted to making my own stand alone python script to write out a file. It looks like this:

fo = open("bar.txt", "wb")
fo.write("this is a test")
fo.close()

It creates the file bar.txt when run from command line.

I am trying to invoke it from my java app like this:

String pythonScriptPath = "/absolute/path/to/foo.py";
String[] cmd = new String[2];
cmd[0] = "python";
cmd[1] = pythonScriptPath;

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd);

No file is written out. What am I missing?

4
  • @Victor2748 read more carefully, he wants to call an external Python program that will handle the file Commented Dec 27, 2014 at 2:55
  • 1
    First things first, don't use Runtime.exec(), use a ProcessBuilder. It allows, from other things, to set the current working directory of a process before starting it, to redirect std{in,out,err} etc. Commented Dec 27, 2014 at 3:10
  • @fge thanks for the tip. I've done ProcessBuilder tests as well. I've had no luck with that either. I just used Runtime.exec() to keep the code snippet short in my example. Commented Dec 27, 2014 at 3:13
  • As far as I'm concerned, I would use a ProcessBuilder and monitor the error output stream to see if the Python program terminates correctly Commented Dec 27, 2014 at 3:14

2 Answers 2

2

The path is specified as a relative path. The file will be created in the current working directory (which is different from the directory that contains the python file or java class/jar/.. file).

Check the directory the java app was run.


By appending following two line to the python code, it will print current working directory:

import os
print(os.getcwd())
Sign up to request clarification or add additional context in comments.

1 Comment

This is the answer. My simple script writes out a file to a different directory than foo.py is. Thanks for helping. For some reason my other file that's part of a larger library isn't writing out a file but this is the answer.
0

Can you ensure that foo.py is being executed? What happens if foo.py doesn't exist? Do you get an error message? If not, you need some way to ensure that you're really executing foo.py.

Have you tried making foo.py do something else, that you would expect to see - i.e.print "Hello world". Once you're certain that "your" foo.py is being executed, then in your fo = open (...) statement, use an absolute path to specify where you want bar.txt to be printed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.