Skip to content

Instantly share code, notes, and snippets.

@zhugw
Created August 19, 2017 03:11
Show Gist options
  • Save zhugw/8d5999a3b2f6aef3ca21f53ca82d054c to your computer and use it in GitHub Desktop.
Save zhugw/8d5999a3b2f6aef3ca21f53ca82d054c to your computer and use it in GitHub Desktop.
Java invoke python script
# 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