Here's my code to execute a jar file in Python:
import os
os.system("java -jar xyz.jar")
I can see the output on terminal, but want to store it in a file. How can I do that?
With subprocess.call you can pipe outputs (stdout, stderr or both) directly into file:
import subprocess
subprocess.call("java -jar xyz.jar", shell=True, stdout=open('outfile.txt', 'wt'), stderr=subprocess.STDOUT)
Note that I added shell=True parameter, which is required if your application requires shell-specific variables (such as where Java is located).
Also note that in the above call, the output streams are handled as follows:
More details on stream configurations are available in subprocess manual page.
shell=True was actually required to correctly locate Java.Don't use os.system, use subprocess instead.
import subprocess
output = subprocess.check_output(["java", "-jar", "xyz.jar"])
file = open('file.txt', 'w+')
file.write(output)
file.close()
>?