utils.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from subprocess import Popen, PIPE
def run_jar(jar_path: str, *args) -> (str, str):
"""
Executes JAR file with provided arguments. Returns stdout and stderr output in string form.
Is blocking operation.
:param jar_path: path to the JAR file. Supports relative paths and user home directory symbol '~'
:param args: arguments passed to the JAR program. Any non-string argument will be converted using str()
:return: stringified output from stdout and stderr streams
"""
# Convert arguments to string form
str_args = [str(arg) for arg in args]
# Open and execute jar
process = Popen(["java", "-jar", jar_path, *str_args], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
# Decoding stdout and stderr from bytes to strings
result_stdout = stdout.decode("utf-8")
result_stderr = stderr.decode("utf-8")
# Usually stdout has redundant '\n' at the end
if result_stdout.endswith("\n"):
result_stdout = result_stdout[:-1]
return result_stdout, result_stderr