I'm calling on some Python modules from Java. The module is using numpy, so I'm using Runtime.getRuntime().exec()
to call Python. In Java I am doing something like this:
File python = new File("/usr/bin/python2.7");
File script = new File("/opt/my_custom_script.py");
String[] cmdArray = new String[] { python.toString(), script.toString(),
"-i infile.txt", "-o outfile.txt" };
Process p = Runtime.getRuntime().exec(cmdArray);
p.waitFor();
if (p.exitValue() != 0) {
throw new Exception(scriptName + " failed with exit code " + p.exitValue());
}
And in Python I've gotten thus far:
def main(argv):
try:
opts, args = getopt.getopt(argv, "i:o:")
except getopt.GetoptError as err:
print(err)
sys.exit(128) # made up number so I know when this happens
sys.exit(0)
if __name__ == "__main__":
main(sys.argv[1:])
Every time I run this I keep on getting the error number I made up, and my Python script runs no further. Calling on Python directly (in bash) gives me no problems.
Where is my disconnect? How would I go about troubleshooting/debugging this?
Your problem is that you are passing two options two the script rather than the four that getopt expects. That is, -i infile.txt
is treated as one option, not, as getopt expects, the two options -i
and infile.txt
, and the same thing is happening to -o outfile.txt
. You can fix this by replacing the line:
String[] cmdArray = new String[] { python.toString(), script.toString(), "-i infile.txt", "-o outfile.txt" };
with this line:
String[] cmdArray = new String[] { python.toString(), script.toString(), "-i", "infile.txt", "-o", "outfile.txt" };
Notice that now -i
and infile.txt
are now separate array elements, as are -o
and -outfile.txt
.