3

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?

2
  • Redirect the output to a file in the terminal, using > ? Commented Jun 1, 2014 at 20:13
  • I want to do hundreds of iterations, so want the process to be automated. Any ideas? Commented Jun 1, 2014 at 20:14

2 Answers 2

6

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:

  • stderr stream is piped to stdout, and
  • stdout is piped to outfile

More details on stream configurations are available in subprocess manual page.

Sign up to request clarification or add additional context in comments.

9 Comments

I tried, but output file is empty. But I can still see output on terminal. Where I might be doing wrong?
No, I'm just doing this.
Wait... I get it now. Your application is probably printing to stderr so you need to pipe stderr stream to the file too.
Check out the edited answer, which takes stderr into account.
Update after a chat: In this case shell=True was actually required to correctly locate Java.
|
0

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()

2 Comments

I get this error: File "pythonScript.py", line 4, in <module> output = subprocess.check_output("java -jar xyz.jar")
Traceback (most recent call last): File "pythonScript.py", line 2, in <module> output = subprocess.check_output("java -jar xyz.jar") File "/usr/lib/python3.4/subprocess.py", line 603, in check_output with Popen(*popenargs, stdout=PIPE, **kwargs) as process: File "/usr/lib/python3.4/subprocess.py", line 848, in init restore_signals, start_new_session) File "/usr/lib/python3.4/subprocess.py", line 1446, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'java -jar xyz.jar'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.