Zafir Stojanovski
Zafir Stojanovski

Reputation: 481

Unable to start python scripts from java code

I've got java code to call a python script

Java

private void visualizeData() {
    try{
        Runtime.getRuntime().exec(“python pyScripts/visualize.py”)
    } catch (IOException e){
        e.printStackTrace();
    }
}

And this is my code for the visualize.py:

visualize.py

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pylot as plt

f = open(“ecoli_data_transformed.txt”,”r”)

fig = plt.figure()
ax = fig.add_subplot(111, projection=‘3d’)

for line in f:
    (a, b, c) = line.split(“\t”)
    a = float(a)
    b = float(b)
    c = float(c)    

    ax.scatter(a,b,c)

ax.setxlabel(‘PCA1’)
ax.setylabel(‘PCA2’)
ax.setzlabel(‘PCA3’)

plt.show()

But it doesn't plot the data.

If I call the test.py script from the java code (test.py is in the same directory as visualize.py), it works:

test.py

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pylot as plt
import numpy as np

np.random.seed(19680801)

def randrange(n, min, vmcx):
    return (vmax - vein)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection=‘3d’)

n = 100

for c, m, slow, high in [(‘r’, ‘o’, -50, -25), (‘b’, ‘^’, -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_xlabel(‘X Label’)
ax.set_ylabel(‘Y Label’)
ax.set_zlabel(‘Z Label’)

plt.show()

What could be the problem?

*NOTE: Calling the visualize.py script from console by 'python visualize.py' works totally fine.

Upvotes: 2

Views: 100

Answers (1)

hasbel
hasbel

Reputation: 26

The relative path that you are passing to the open() command in your python script is probably the problem.

Your Java program is located in a different directory than the one your Python program is located in. When it starts the python script, the current path is still the path to the Java program.

This means that Python is unable to find the relative path to the file you are trying to open, ecoli_data_transformed.txt.

A work around would be to include the complete path to your .txt file:

f = open(“C:\\path\\to\\your\\file\\ecoli_data_transformed.txt”,”r”)

A better solution would be to determine it programatically:

import os

file_path = os.path.dirname(__file__)
f = open(file_path + "\\ecoli_data_transformed.txt”,”r”)

Upvotes: 1

Related Questions