Created
August 19, 2017 03:11
Java invoke python script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Java invoke Python script | |
## Python script | |
``` | |
python test.py | |
hello world | |
# with parameter | |
python test.py foo bar | |
hello world | |
['foo', 'bar'] | |
``` | |
## Java code | |
``` | |
ProcessBuilder builder = new ProcessBuilder(); | |
//builder.command("python", "test.py"); | |
builder.command("python", "test.py","foo","bar"); | |
Process process = builder.start(); | |
process.waitFor(); | |
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); | |
bufferedReader.lines().forEach(System.out::println); | |
``` | |
## Warning | |
if python script has any error, java just cannot read anything and nothing output, it cannot know what's wrong, e.g | |
``` | |
python test.py | |
Traceback (most recent call last): | |
File "test.py", line 5, in <module> | |
print(1/0) | |
ZeroDivisionError: integer division or modulo by zero | |
python non_exist.py | |
/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'non_exist.py': [Errno 2] No such file or directory | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment