Changing path for running Python code via Java
<p>I implemented Python app, and Java app.
Let's assume that my Python app is returned True as a result.</p>

<p>I would like to run Python app via Java app, receive the results from Python app into my Java app and make additional calculations in my Java app.</p>

<p>I use Process in Java for this mission.
In my example the Python app is running with config.ini file as a parameter.</p>

<pre><code>String path = "C:\\Python_Project\\run_app.py configuration\\config.ini";
Process p = Runtime.getRuntime().exec("python " + path);
</code></pre>

<p>It is not working. The Java app is not failed by I do not receive anything interesting from Python app. </p>

<p>I decided to run it via Command Prompt and found that the run is failed because in one of my internal files I used import like this:
    from inner_module import Object1</p>

<p>Maybe is this the problem? I should run it from Python app directory? But how?</p>

<p>I have two questions:</p>

<ol>
<li><p>Is it a way to change the path for running my python app? I run the Java app from my Java app directory and I have to run the Python app inside the Python app directory?How can I change the perspective? </p></li>
<li><p>Is the use of Process and exec is good? Should I use something else?
How I can use the Process for getting the True value Python app sent?</p></li>
</ol>

<p>You can try <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html" rel="nofollow">ProcessBuilder</a> which allows you to set the working directory. Something like:</p>

<pre><code>ProcessBuilder pb = new ProcessBuilder(program, argument);
pb.directory(new File("path/to/python/directory"));
Process process = pb.start();
</code></pre>

<p>You can obtain the script's output by reading from process.getInputStream()</p>

<pre><code>BufferedReader reader = new BufferedReader(
    new InputStreamReader(process.getIntputStream()));

String output;
while((output=reader.readLine()) != null)
    System.out.println(output);
</code></pre>

java python