Tgsmith61591 Tgsmith61591 - 1 year ago 119
Python Question

Python ImportError when calling Python script from Java

First off, there is a similar question here that wasn't ever really resolved.

I have a Python script that I want to execute from within my Java code. When I run the Python script on its own, it works properly. When I try to execute it from a Java process, I get an ImportError:

Traceback (most recent call last):
File "", line 3, in <module>
from omgeo import Geocoder
ImportError: No module named omgeo

Per a suggestion from the linked question, I appended a direct path to the module in my Python import section to make sure the interpreter knows where to look, yet it still won't work:

import sys, os
from omgeo import Geocoder

My next move was to call the python script from a bash script (which again, works on its own), but when I call the bash script from Java, the same error persists. The issue, therefore seems to be on Java's end. Here is my java code:

Process p = runner.exec("python");

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String stdReader = null;
//Read output of command:
while((stdReader = stdInput.readLine())!=null) {

//Read any command errors:
while((stdReader = stdError.readLine())!=null) {

Is there anything wrong with my Java code or is this a bug? I appreciate any pointers.

Answer Source

I solved it. It looks like ProcessBuilder requires the full path not only to the python file itself, but to python:


This solves the issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download